> 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/ja/api-reference/zu-zhi-he-cheng-yuan.md).

# 組織とメンバー

### アカウント登録 <a href="#auth-registration-create" id="auth-registration-create"></a>

POST `/api/v1/auth/registration/`

#### リクエストボディ

**リクエストパラメータ**

| フィールド         | 型                                 | 必須  | 説明 |
| ------------- | --------------------------------- | --- | -- |
| email         | string (email)                    | はい  |    |
| password1     | string                            | はい  |    |
| password2     | string                            | はい  |    |
| name          | string                            | はい  |    |
| company       | string                            | はい  |    |
| referralCode  | string                            | いいえ |    |
| authSource    | object (2 個のプロパティを含みます: id, name) | いいえ |    |
| authSource.id | string (uuid)                     | はい  |    |

**リクエストスキーマの例**

```typescript
{
  "email": string (email)
  "password1": string
  "password2": string
  "name": string
  "company": string
  "referralCode"?: string // 任意
  "authSource"?:  // 任意
  {
    "id": string (uuid)
  }
}
```

**リクエストの値の例**

```json
{
  "email": "user@example.com",
  "password1": "サンプル文字列",
  "password2": "サンプル文字列",
  "name": "サンプル名",
  "company": "サンプル文字列",
  "referralCode": "サンプル文字列",
  "authSource": {
    "id": "550e8400-e29b-41d4-a716-446655440000"
  }
}
```

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/auth/registration/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password1": "サンプル文字列",
    "password2": "サンプル文字列",
    "name": "サンプル名",
    "company": "サンプル文字列",
    "referralCode": "サンプル文字列",
    "authSource": {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "email": "user@example.com",
    "password1": "サンプル文字列",
    "password2": "サンプル文字列",
    "name": "サンプル名",
    "company": "サンプル文字列",
    "referralCode": "サンプル文字列",
    "authSource": {
      "id": "550e8400-e29b-41d4-a716-446655440000"
    }
  };

axios.post("https://api.maiagent.ai/api/v1/auth/registration/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "email": "user@example.com",
    "password1": "サンプル文字列",
    "password2": "サンプル文字列",
    "name": "サンプル名",
    "company": "サンプル文字列",
    "referralCode": "サンプル文字列",
    "authSource": {
        "id": "550e8400-e29b-41d4-a716-446655440000"
    }
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/auth/registration/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'email' => 'user@example.com',
            'password1' => 'サンプル文字列',
            'password2' => 'サンプル文字列',
            'name' => 'サンプル名',
            'company' => 'サンプル文字列',
            'referralCode' => 'サンプル文字列',
            'authSource' => [
                'id' => '550e8400-e29b-41d4-a716-446655440000'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 201**

**レスポンススキーマの例**

```typescript
{
  "email": string (email)
  "password1": string
  "password2": string
  "name": string
  "company": string
  "referralCode"?: string // 任意
  "authSource"?:  // 任意
  {
    "id": string (uuid)
    "name": string
  }
}
```

**レスポンスの値の例**

```json
{
  "email": "response@example.com",
  "password1": "レスポンス文字列",
  "password2": "レスポンス文字列",
  "name": "レスポンス文字列",
  "company": "レスポンス文字列",
  "referralCode": "レスポンス文字列",
  "authSource": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  }
}
```

***

### パスワードの変更 <a href="#auth-password-change-create" id="auth-password-change-create"></a>

POST `/api/v1/auth/password/change/`

#### リクエストボディ

**リクエストパラメータ**

| フィールド        | 型      | 必須 | 説明 |
| ------------ | ------ | -- | -- |
| oldPassword  | string | はい |    |
| newPassword1 | string | はい |    |
| newPassword2 | string | はい |    |

**リクエストスキーマの例**

```typescript
{
  "oldPassword": string
  "newPassword1": string
  "newPassword2": string
}
```

**リクエストの値の例**

```json
{
  "oldPassword": "サンプル文字列",
  "newPassword1": "サンプル文字列",
  "newPassword2": "サンプル文字列"
}
```

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/auth/password/change/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "oldPassword": "サンプル文字列",
    "newPassword1": "サンプル文字列",
    "newPassword2": "サンプル文字列"
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "oldPassword": "サンプル文字列",
    "newPassword1": "サンプル文字列",
    "newPassword2": "サンプル文字列"
  };

axios.post("https://api.maiagent.ai/api/v1/auth/password/change/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "oldPassword": "サンプル文字列",
    "newPassword1": "サンプル文字列",
    "newPassword2": "サンプル文字列"
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/auth/password/change/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'oldPassword' => 'サンプル文字列',
            'newPassword1' => 'サンプル文字列',
            'newPassword2' => 'サンプル文字列'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

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

**レスポンスの値の例**

```json
{
  "detail": "レスポンス文字列"
}
```

***

### 新しい組織を作成します <a href="#organizations-create" id="organizations-create"></a>

POST `/api/v1/organizations/`

#### リクエストボディ

**リクエストパラメーター**

| フィールド         | 型               | 必須  | 説明                                |
| ------------- | --------------- | --- | --------------------------------- |
| name          | string          | はい  | 組織名                               |
| compact\_logo | string (binary) | いいえ | コンパクト版ロゴ（任意、Enterprise プランのみ利用可能） |
| full\_logo    | string (binary) | いいえ | フル版ロゴ（任意、Enterprise プランのみ利用可能）    |

**リクエストスキーマの例**

```typescript
{
  "name": string // 組織名
  "compact_logo"?: string (binary) // コンパクト版ロゴ（任意、Enterprise プランのみ利用可能） (任意)
  "full_logo"?: string (binary) // フル版ロゴ（任意、Enterprise プランのみ利用可能） (任意)
}
```

**リクエスト値の例**

```json
{
  "name": "My Organization"
}
```

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/organizations/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My Organization"
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "name": "My Organization"
  };

axios.post("https://api.maiagent.ai/api/v1/organizations/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "name": "My Organization"
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/organizations/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => 'My Organization'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 201**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "name": string
  "createdAt": string (timestamp)
  "compactLogo"?: string (uri) // 任意
  "fullLogo"?: string (uri) // 任意
  "themePrimaryColor"?: // 異なる型になる場合があります (任意)
  string // ボタンやリンクなどの要素に使用する UI テーマカラーです（HEX 形式、例：#0960bd）。空欄は未設定を意味し、フロントエンドではシステムのブランドのプライマリカラーを使用します (任意)
  "usageStatistics": object
  "organizationPlan": object
  "creditWallet": object // Return credit wallet with ID only.
  "maigptInboxId": string (uuid)
  "canUseCustomElasticsearch": boolean // Allow this organization to configure custom Elasticsearch endpoints for knowledge bases.
  "canUseVoiceAgent": boolean // Allow this organization to use voice agent features.
  "canUseMeetingRecords": boolean // Allow this organization to use meeting records features.
  "canUseCallCenter": boolean // Allow this organization to use call center features.
  "canUseHookSystem": boolean // Manual override to grant this organization the hook system regardless of plan. Enterprise-plan organizations get access automatically without this flag. Layered under the global Config.hook_system_enabled switch: it must also be enabled.
  "canUseAiGateway": boolean // Allow this organization to call the OpenAI-compatible `/api/v1/chat/completions` Gateway. On by default for license installs, otherwise off until a platform admin enables it.
  "canUseGroupAssistant": boolean // Allow this organization to use the personal secretary (its LINE group features). Off by default; the organization admin still switches the assistant on in Admin.
  "canUseAgentTeams": boolean // Read-only projection of the platform-wide Agent Teams switch (Config.enable_agent_teams). Not a per-organization flag; member-level access is still governed by RBAC.
  "canUseFileLibrary": boolean // Allow this organization to use the file library.
  "canUseFileOnlineEditing": boolean // Enable online editing in the file library (P7): the text editor and upload-new-version entries. Requires can_use_file_library to also be on.
  "canUseOfficeOnlineEditing": boolean // Enable Office (xlsx/docx/pptx) online editing in the file library (P7 S9). Requires can_use_file_online_editing to also be on.
  "canUseRolePermissionGovernance": boolean // Always true: batch role permission settings and the effective permissions view are available to every organization. Kept for clients that still read it; access is governed by organization_overview_access.
  "enableAgentMemory": boolean // Enable persistent cross-conversation memory for agents in this organization. When off, agents use only in-session memory. On by default on SaaS; license installs remain opt-in. Members can still turn it off for themselves in Profile > AI Memory.
  "hideChinaModels"?: boolean // When on, platform models whose developer is based in China (including ones added later) cannot be used in this organization: model menus, assistants, the API and AI Gateway exclude them, and live transcription lists China-developed speech engines as unavailable. Off by default; turn it on for public-sector or other organizations that must not use them. (任意)
  "autoActivateNewChatbotChannels"?: boolean // Initial state of the web chat and API channels of a new chatbot whose creator did not set them (duplicates, templates and API calls without the values included). When on, they start active; when off (the platform default), they start inactive until a member turns them on. The creator can still override both channels in the New Chatbot dialog or the create API. The backstage (admin) channel is always active. Changing this does not affect existing chatbots. (任意)
  "gatewayServiceFeePercent": string (decimal) // Markup applied on top of the token price when billing MaiAgent-managed models called through the AI Gateway (/v1/chat/completions and /v1/embeddings). Managed gateway markup only; the organization's own models (BYOK / self-hosted) are billed via the AI Gateway traffic fee percent instead.
  "gatewayTrafficFeePercent": string (decimal) // Pass-through fee for calls that run on this organization's own AI Gateway models (BYOK / self-hosted): charged as the call's total tokens (input, output, and prompt-cache) x this percent in credits, with no LLM token pricing. Adjustable per organization; changes apply to new calls only.
  "platformProcessingFeePercent": string (decimal) // Surcharge on every credit consumption of this organization, billed as a separate "Platform Processing Fee" line equal to the consumed credits x this percent. 0 disables the fee. Applies to new consumption only; the percent is shown read-only on the customer pricing page.
  "platformProcessingFeeEnabled": boolean // Whether new consumption of this organization accrues the platform processing fee. The percent is exposed read-only as platform_processing_fee_percent.
  "isTrial": boolean // トライアル期間中かどうかを示します。組織にトライアルプランが1つだけあり、現在有効な場合に true になります
  "expirationDays": integer // 有効期限が切れてからの日数です。正の数は経過日数、null は有効期限前または無期限のプランを表します
  "showTrialBanner": boolean // フロントエンドでトライアル／無料プランのバナーを表示するかどうかを制御します
  "agentScheduleMinIntervalSeconds": integer // プラットフォームで設定するスケジュールの最小実行間隔（秒）です。作成・編集時にフロントエンドで下限を表示しますが、実際の検証はスケジュール API で行います
  "noActivePlanDays": integer // Consecutive days without an active paid plan. null when cleanup is disabled.
  "cleanupRemainingDays": integer // Days remaining before organization data is permanently deleted. null when cleanup is disabled, org has an active paid plan, or no_active_plan_days is 0.
  "estimatedCleanupDate": string // ISO date when organization data will be permanently deleted. null when cleanup_remaining_days is null.
  "approvalStatus":  // Trial-eligibility review status. Only approved organizations can receive a trial plan when organization approval is enabled. Paid plan activation auto-approves the organization.

* `pending` - Pending Review
* `approved` - Approved
* `rejected` - Rejected
  {
  }
  "companyName"?: string // Applicant-reported company name collected at organization creation for approval review. (任意)
  "taxId"?: // 異なる型になる場合があります (任意)
  string // Applicant-reported business tax ID (8 digits, optional). Stored as-is; not verified. (任意)
  "contactPhone"?: string // Applicant-reported contact phone collected at organization creation for approval review. (任意)
  "applicationMetadata"?: object // Extra applicant-reported key-value fields collected at organization creation. Lets the frontend collect additional review fields without a schema migration; the core review fields (company name, tax ID, contact phone) stay as named columns. (任意)
  "invitationCode"?: string // 任意
  "ipAllowlistEnabled": boolean // Restrict this organization to the source IPs listed in allowed_ip_cidrs. Layered under the global Config.ip_allowlist_enforcement_enabled switch: both must be enabled. Disabled by default so existing organizations keep unrestricted access.
  "allowedIpCidrs": string // Source IPs or CIDRs allowed to reach this organization, one per line (e.g. 203.0.113.0/24); commas also work. While the IP allowlist is enabled, an empty list rejects everything. A non-empty list whose entries are all invalid rejects everything rather than silently reverting to unrestricted, so a typo cannot quietly disable the protection. Matching uses the load-balancer-appended client IP.
  "enforceIpAllowlistOnAdminUi": boolean // Apply the allowlist to browser sessions: the admin console and its WebSocket connections. Only takes effect while ip_allowlist_enabled is on.
  "enforceIpAllowlistOnApiKey": boolean // Apply the allowlist to Open API (Api-Key) and AI Gateway (Bearer) requests. Only takes effect while ip_allowlist_enabled is on.
}
```

**レスポンス値の例**

```json
{
  "id": "5b01e0b9-0b0e-4079-8150-d12015576d2c",
  "name": "My Organization",
  "createdAt": "1748336288000",
  "compactLogo": null,
  "fullLogo": null,
  "usageStatistics": {
    "chatbotsCount": 0,
    "countableChatbotsCount": 0,
    "exemptChatbotsByMode": {},
    "canCreateChatbot": true,
    "createChatbotLimit": 1,
    "currentMonthWordsCountTotal": 1000000,
    "currentMonthUsedWordsCountTotal": 0,
    "currentMonthUsedConversationsCountTotal": 0,
    "availableUploadFilesSizeTotal": 104857600,
    "usedUploadFileSizeTotal": 0
  },
  "organizationPlan": {
    "id": "cac825e8-cb9b-4a16-b440-4ff6b2e73911",
    "planName": "無料プラン",
    "planType": "free",
    "expiredAt": null
  },
  "maigptInboxId": null,
  "canUseCustomElasticsearch": false,
  "isTrial": true,
  "expirationDays": null
}
```

***

### 指定した組織へのメンバー追加 <a href="#organizations-members-create" id="organizations-members-create"></a>

POST `/api/v1/organizations/{organizationPk}/members/`

#### パラメータ

| パラメータ名           | 必須 | 型      | 説明                       |
| ---------------- | -- | ------ | ------------------------ |
| `organizationPk` | ✅  | string | この組織 ID を識別する UUID 文字列です |

#### リクエストボディ

**リクエストパラメータ**

| フィールド        | 型              | 必須  | 説明 |
| ------------ | -------------- | --- | -- |
| email        | string (email) | はい  |    |
| organization | string (uuid)  | いいえ |    |

**リクエストスキーマの例**

```typescript
{
  "email": string (email)
  "organization"?: string (uuid) // 任意
}
```

**リクエストの値の例**

```json
{
  "organization": "613c86f7-a45f-4e29-b255-29caff89de32",
  "is_owner": false
}
```

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "organization": "613c86f7-a45f-4e29-b255-29caff89de32",
    "is_owner": false
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "organization": "613c86f7-a45f-4e29-b255-29caff89de32",
    "is_owner": false
  };

axios.post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "organization": "613c86f7-a45f-4e29-b255-29caff89de32",
    "is_owner": False
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'organization' => '613c86f7-a45f-4e29-b255-29caff89de32',
            'is_owner' => false
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 201**

**レスポンススキーマの例**

```typescript
{
  "organization": string (uuid) // 組織 ID
  "is_owner": boolean // 組織の所有者かどうかを示します
}
```

**レスポンスの値の例**

```json
{
  "organization": "613c86f7-a45f-4e29-b255-29caff89de32",
  "is_owner": false
}
```

***

### メンバーの一括インポート <a href="#organizations-members-bulk-import-create" id="organizations-members-bulk-import-create"></a>

POST `/api/v1/organizations/{organizationPk}/members/bulk-import/`

{% hint style="info" %}
`multipart/form-data` で `file`（.xlsx）をアップロードします。`Email(required)` 列は必須、`Name` 列は任意です。1 回につき最大 25,000 行（ヘッダー行を除く）まで取り込めます。上限を超えるとファイル全体が取り込まれず、`400` が返されます。ファイルを分割してインポートしてください。いずれかの行で Email が空欄または無効な場合や、Name が 255 文字を超える場合も、ファイル全体が取り込まれません。この場合、`400` の `detail` は行ごとのエラーを列挙した文字列の配列です。`Email(required)` 列がない場合や、ファイルにデータ行がない場合、`detail` は単一の文字列です。.xlsx 以外のファイルの場合、エラーは `file` フィールドに返されます。同じ Email が複数回出現した場合は、最初の 1 件だけが処理されます。Email がまだ組織に登録されていないユーザーは組織に追加され、`added` に計上されます。Name はそのユーザーの組織内の名前になります（今回新規作成されたアカウントでは、Name がアカウント名にも使用されます。未入力の場合は Email のプレフィックスを使用します）。Email が既存メンバーのものである場合は、インポート実行者の権限に応じて処理されます。組織のオーナーがインポートした場合、Name が現在の表示名と異なれば、そのメンバーの組織内の名前を更新します（`updated`）。Name が空欄または同じ場合は変更しません（`unchanged`）。Name が異なっていても、メンバーが SCIM 同期で管理されている場合は更新しません（`scimSkipped`）。オーナー以外がインポートした場合は従来の動作を維持し、既存メンバーをスキップして名前は更新しません（`skippedExisting`）。`importerIsOwner` は、インポート実行者がオーナーかどうかを示します。更新されるのは組織内の名前だけで、既存メンバーのアカウント名は変更されません。`created` の意味は従来どおり、新規追加メンバーと既存メンバーの合計です。これは `added`、`updated`、`unchanged`、`scimSkipped`、`skippedExisting` の 5 項目の合計に等しく、`created` のみを読み取る連携は変更不要です。`message` は行ごとのメッセージです。オーナーがインポートした場合は「すでに組織に所属しています」に代わり、「N 行目：名前を更新しました」「N 行目：変更はありません」「N 行目：SCIM 同期で管理されているため、更新しませんでした」が返されます。オーナー以外がインポートした場合は、従来のメッセージを維持します。
{% endhint %}

#### パラメーター

| パラメーター名          | 必須 | 型      | 説明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/bulk-import/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -F "file=@example_file.xlsx"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// FormData オブジェクトを作成します
const formData = new FormData();
// 実際のファイルに置き換えてください
formData.append('file', /* 実際のファイルオブジェクト */, 'example_file.xlsx');

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    ...formData.getHeaders()
  }
};

axios.post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/bulk-import/", formData, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# ファイルとフォームデータを準備します
files = {
    'file': ('example_file.xlsx', open('example_file.xlsx', 'rb'), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
}

response = requests.post(url, files=files, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/bulk-import/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ],
        'multipart' => [
            [
                'name' => 'file',
                'contents' => fopen('example_file.xlsx', 'r'),
                'filename' => 'example_file.xlsx'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 201**

**レスポンススキーマの例**

```typescript
{
  "created": integer // 処理したメンバーの総数です（新規作成と既存のメンバーを含みます）
  "added": integer // 組織に新規追加されたメンバー数です
  "updated": integer // オーナーによるインポートで組織内の名前を更新した既存メンバー数です
  "unchanged": integer // オーナーによるインポートで、Name が空欄または現在の表示名と同じため変更しなかった既存メンバー数です
  "scimSkipped": integer // オーナーによるインポートで、SCIM 同期で管理されているため名前を更新しなかった既存メンバー数です
  "skippedExisting": integer // オーナー以外によるインポートで、すでに組織に所属しているためスキップしたメンバー数です。オーナーによるインポートでは 0 です
  "importerIsOwner": boolean // インポート実行者が組織のオーナーかどうかを示します
  "message"?: [ // 行ごとのメッセージです（ない場合は返されません）。オーナーによるインポート：「N 行目：名前を更新しました／変更はありません／SCIM 同期で管理されているため、更新しませんでした」。オーナー以外によるインポート：すでに組織に所属しているためスキップした行番号と email を列挙します（任意）
    string
  ]
}
```

**レスポンス値の例**

```json
{
  "created": 5,
  "added": 2,
  "updated": 1,
  "unchanged": 1,
  "scimSkipped": 1,
  "skippedExisting": 0,
  "importerIsOwner": true,
  "message": [
    "2 行目：名前を更新しました",
    "3 行目：変更はありません",
    "5 行目：SCIM 同期で管理されているため、更新しませんでした"
  ]
}
```

**ステータスコード: 400 - 検証エラーです。ファイル全体が取り込まれません**

**レスポンススキーマの例**

```typescript
{
  "detail"?: // 型が異なる場合があります（任意）
  array[string] // ファイル全体が取り込まれない理由です。文字列の配列：行ごとのエラー（Email が空欄、Name が 255 文字を超える場合など）、または 1 回あたり 25,000 行の上限超過です。文字列：必須列がない場合、またはファイルにデータ行がない場合です（任意）
  "file"?: [ // ファイルが .xlsx 形式ではありません（任意）
    string
  ]
}
```

**レスポンス値の例**

```json
{
  "detail": [
    "3 行目：Email は空欄にできません",
    "5 行目：Email は空欄にできません"
  ]
}
```

***

### 組織一覧の取得 <a href="#organizations-list" id="organizations-list"></a>

GET `/api/v1/organizations/`

#### パラメータ

| パラメータ名       | 必須 | 型       | 説明                                             |
| ------------ | -- | ------- | ---------------------------------------------- |
| `page`       | ❌  | integer | A page number within the paginated result set. |
| `pageSize`   | ❌  | integer | Number of results to return per page.          |
| `pagination` | ❌  | string  | ページネーションを行うかどうか (true/false)                   |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/?page=1&pageSize=1&pagination=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/organizations/?page=1&pageSize=1&pagination=example", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/organizations/?page=1&pageSize=1&pagination=example"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/organizations/?page=1&pageSize=1&pagination=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string (uuid)
      "name": string
      "createdAt": string (timestamp)
      "memberCreatedAt": string (timestamp)
      "approvalStatus": string
    }
  ]
}
```

**レスポンスの値の例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス文字列",
      "createdAt": "レスポンス文字列",
      "memberCreatedAt": "レスポンス文字列",
      "approvalStatus": "レスポンス文字列"
    }
  ]
}
```

***

### 特定の組織情報を取得 <a href="#organizations-retrieve" id="organizations-retrieve"></a>

GET `/api/v1/organizations/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                    |
| ------ | -- | ------ | --------------------- |
| `id`   | ✅  | string | この組織を識別する UUID 文字列です。 |

#### コード例

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

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

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "name": string
  "createdAt": string (timestamp)
  "compactLogo"?: string (uri) // 任意
  "fullLogo"?: string (uri) // 任意
  "themePrimaryColor"?: // 異なる型を取る場合があります (任意)
  string // ボタンやリンクなどの要素に使用する UI テーマカラーです（HEX 形式、例：#0960bd）。空欄の場合は未設定とみなされ、フロントエンドではシステムのブランドのメインカラーが代わりに使用されます (任意)
  "usageStatistics": object
  "organizationPlan": object
  "creditWallet": object // Return credit wallet with ID only.
  "maigptInboxId": string (uuid)
  "canUseCustomElasticsearch": boolean // Allow this organization to configure custom Elasticsearch endpoints for knowledge bases.
  "canUseVoiceAgent": boolean // Allow this organization to use voice agent features.
  "canUseMeetingRecords": boolean // Allow this organization to use meeting records features.
  "canUseCallCenter": boolean // Allow this organization to use call center features.
  "canUseHookSystem": boolean // Manual override to grant this organization the hook system regardless of plan. Enterprise-plan organizations get access automatically without this flag. Layered under the global Config.hook_system_enabled switch: it must also be enabled.
  "canUseAiGateway": boolean // Allow this organization to call the OpenAI-compatible `/api/v1/chat/completions` Gateway. On by default for license installs, otherwise off until a platform admin enables it.
  "canUseGroupAssistant": boolean // Allow this organization to use the personal secretary (its LINE group features). Off by default; the organization admin still switches the assistant on in Admin.
  "canUseAgentTeams": boolean // Read-only projection of the platform-wide Agent Teams switch (Config.enable_agent_teams). Not a per-organization flag; member-level access is still governed by RBAC.
  "canUseFileLibrary": boolean // Allow this organization to use the file library.
  "canUseFileOnlineEditing": boolean // Enable online editing in the file library (P7): the text editor and upload-new-version entries. Requires can_use_file_library to also be on.
  "canUseOfficeOnlineEditing": boolean // Enable Office (xlsx/docx/pptx) online editing in the file library (P7 S9). Requires can_use_file_online_editing to also be on.
  "canUseRolePermissionGovernance": boolean // Always true: batch role permission settings and the effective permissions view are available to every organization. Kept for clients that still read it; access is governed by organization_overview_access.
  "enableAgentMemory": boolean // Enable persistent cross-conversation memory for agents in this organization. When off, agents use only in-session memory. On by default on SaaS; license installs remain opt-in. Members can still turn it off for themselves in Profile > AI Memory.
  "hideChinaModels"?: boolean // When on, platform models whose developer is based in China (including ones added later) cannot be used in this organization: model menus, assistants, the API and AI Gateway exclude them, and live transcription lists China-developed speech engines as unavailable. Off by default; turn it on for public-sector or other organizations that must not use them. (任意)
  "autoActivateNewChatbotChannels"?: boolean // Initial state of the web chat and API channels of a new chatbot whose creator did not set them (duplicates, templates and API calls without the values included). When on, they start active; when off (the platform default), they start inactive until a member turns them on. The creator can still override both channels in the New Chatbot dialog or the create API. The backstage (admin) channel is always active. Changing this does not affect existing chatbots. (任意)
  "gatewayServiceFeePercent": string (decimal) // Markup applied on top of the token price when billing MaiAgent-managed models called through the AI Gateway (/v1/chat/completions and /v1/embeddings). Managed gateway markup only; the organization's own models (BYOK / self-hosted) are billed via the AI Gateway traffic fee percent instead.
  "gatewayTrafficFeePercent": string (decimal) // Pass-through fee for calls that run on this organization's own AI Gateway models (BYOK / self-hosted): charged as the call's total tokens (input, output, and prompt-cache) x this percent in credits, with no LLM token pricing. Adjustable per organization; changes apply to new calls only.
  "platformProcessingFeePercent": string (decimal) // Surcharge on every credit consumption of this organization, billed as a separate "Platform Processing Fee" line equal to the consumed credits x this percent. 0 disables the fee. Applies to new consumption only; the percent is shown read-only on the customer pricing page.
  "platformProcessingFeeEnabled": boolean // Whether new consumption of this organization accrues the platform processing fee. The percent is exposed read-only as platform_processing_fee_percent.
  "isTrial": boolean // トライアル期間中かどうかを示します。組織にトライアルプランが 1 つだけあり、現在有効な場合に true になります
  "expirationDays": integer // 有効期限が切れてからの日数です。正の数は期限切れからの日数を表し、null は期限前または無期限のプランを表します
  "showTrialBanner": boolean // フロントエンドでトライアル/無料プランのバナーを表示するかどうかを制御します
  "agentScheduleMinIntervalSeconds": integer // プラットフォームで設定されたスケジュールの最小実行間隔（秒）です。スケジュールの作成／編集時にフロントエンドで下限として表示され、実際の検証はスケジュール API で行われます
  "noActivePlanDays": integer // Consecutive days without an active paid plan. null when cleanup is disabled.
  "cleanupRemainingDays": integer // Days remaining before organization data is permanently deleted. null when cleanup is disabled, org has an active paid plan, or no_active_plan_days is 0.
  "estimatedCleanupDate": string // ISO date when organization data will be permanently deleted. null when cleanup_remaining_days is null.
  "approvalStatus":  // Trial-eligibility review status. Only approved organizations can receive a trial plan when organization approval is enabled. Paid plan activation auto-approves the organization.

* `pending` - Pending Review
* `approved` - Approved
* `rejected` - Rejected
  {
  }
  "companyName"?: string // Applicant-reported company name collected at organization creation for approval review. (任意)
  "taxId"?: // 異なる型を取る場合があります (任意)
  string // Applicant-reported business tax ID (8 digits, optional). Stored as-is; not verified. (任意)
  "contactPhone"?: string // Applicant-reported contact phone collected at organization creation for approval review. (任意)
  "applicationMetadata"?: object // Extra applicant-reported key-value fields collected at organization creation. Lets the frontend collect additional review fields without a schema migration; the core review fields (company name, tax ID, contact phone) stay as named columns. (任意)
  "invitationCode"?: string // 任意
  "ipAllowlistEnabled": boolean // Restrict this organization to the source IPs listed in allowed_ip_cidrs. Layered under the global Config.ip_allowlist_enforcement_enabled switch: both must be enabled. Disabled by default so existing organizations keep unrestricted access.
  "allowedIpCidrs": string // Source IPs or CIDRs allowed to reach this organization, one per line (e.g. 203.0.113.0/24); commas also work. While the IP allowlist is enabled, an empty list rejects everything. A non-empty list whose entries are all invalid rejects everything rather than silently reverting to unrestricted, so a typo cannot quietly disable the protection. Matching uses the load-balancer-appended client IP.
  "enforceIpAllowlistOnAdminUi": boolean // Apply the allowlist to browser sessions: the admin console and its WebSocket connections. Only takes effect while ip_allowlist_enabled is on.
  "enforceIpAllowlistOnApiKey": boolean // Apply the allowlist to Open API (Api-Key) and AI Gateway (Bearer) requests. Only takes effect while ip_allowlist_enabled is on.
}
```

**レスポンスのサンプル値**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "createdAt": "レスポンス文字列",
  "compactLogo": "https://example.com/file.jpg",
  "fullLogo": "https://example.com/file.jpg",
  "themePrimaryColor": "レスポンス文字列",
  "usageStatistics": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンスのサンプル名",
    "description": "レスポンスのサンプル説明"
  },
  "organizationPlan": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンスのサンプル名",
    "description": "レスポンスのサンプル説明"
  },
  "creditWallet": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンスのサンプル名",
    "description": "レスポンスのサンプル説明"
  },
  "maigptInboxId": "550e8400-e29b-41d4-a716-446655440000",
  "canUseCustomElasticsearch": false,
  "canUseVoiceAgent": false,
  "canUseMeetingRecords": false,
  "canUseCallCenter": false,
  "canUseHookSystem": false,
  "canUseAiGateway": false,
  "canUseGroupAssistant": false,
  "canUseAgentTeams": false,
  "canUseFileLibrary": false,
  "canUseFileOnlineEditing": false,
  "canUseOfficeOnlineEditing": false,
  "canUseRolePermissionGovernance": false,
  "enableAgentMemory": false,
  "hideChinaModels": false,
  "autoActivateNewChatbotChannels": false,
  "gatewayServiceFeePercent": "レスポンス文字列",
  "gatewayTrafficFeePercent": "レスポンス文字列",
  "platformProcessingFeePercent": "レスポンス文字列",
  "platformProcessingFeeEnabled": false,
  "isTrial": false,
  "expirationDays": 456,
  "showTrialBanner": false,
  "agentScheduleMinIntervalSeconds": 456,
  "noActivePlanDays": 456,
  "cleanupRemainingDays": 456,
  "estimatedCleanupDate": "レスポンス文字列",
  "approvalStatus": {},
  "companyName": "レスポンス文字列",
  "taxId": "レスポンス文字列",
  "contactPhone": "レスポンス文字列",
  "applicationMetadata": null,
  "invitationCode": "レスポンス文字列",
  "ipAllowlistEnabled": false,
  "allowedIpCidrs": "レスポンス文字列",
  "enforceIpAllowlistOnAdminUi": false,
  "enforceIpAllowlistOnApiKey": false
}
```

***

### 現在のユーザーの詳細情報を取得 <a href="#users-current-retrieve" id="users-current-retrieve"></a>

GET `/api/v1/users/current/`

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/users/current/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/users/current/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/users/current/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/users/current/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "avatar"?: string (uri) // 任意
  "originalAvatar"?: string (uri) // ユーザーがアップロードしたアバターの元画像（長辺は 2048px 以内に制限）。編集のたびにこの画像から切り抜き直すため、切り抜き済みの画像をさらに切り抜くことによる劣化の蓄積を防ぎます。この機能のリリース前の既存データは空で、補完されません (任意)
  "avatarCropBox"?: object // 前回の切り抜き枠の元画像上での位置とサイズ（x/y/width/height、rotate/scale_x/scale_y は任意）。座標は保存されている元画像を基準とします (任意)
  "name": string
  "email": string (email)
  "authSource": 
  {
    "id": string (uuid)
    "name": string
  }
  "company"?: string // 任意
  "invitationCode"?: // 複数の型の可能性あり (任意)
  string // 任意
  "apiKeys": [ // ユーザーが指定した組織内で持つ API キーの一覧を取得します。

フロー:
1. リクエストから現在の組織インスタンスを取得します
2. 組織インスタンスがない場合（通常はサードパーティ SSO ログイン時）、ユーザーの認証ソースを使って
   その認証ソースのデフォルト組織（is_auth_source_default_organization=True）を検索します

注意:
- サードパーティ SSO ログイン時、リクエストには organization_instance が含まれません
- auth_source と is_auth_source_default_organization フラグを使って組織を特定する必要があります
    object
  ]
  "permissions": object // 現在の組織におけるユーザーの権限を取得します（親子のネスト構造）。
  "resourcePermissions": object // 現在の組織におけるユーザーのリソース作成権限を取得します。
  "isOwner": boolean // ユーザーが現在の組織で Owner かどうかを判定します。
  "maigptCapabilities": object // MaiGPT におけるメンバーの有効な組み込み機能の権限（ロール権限の解決結果）。フロントエンドでの表示/非表示に使用します。

メンバーコンテキストがない（組織に紐付いていない）場合、解決結果はすべて有効になります。これは resolver の「データ欠落時にロックしない」方針と一致します。
フロントエンドでの非表示は UX 上の層にすぎず、正式な制御は返信パスの gate で行われます。
}
```

**レスポンスの値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "avatar": "https://example.com/file.jpg",
  "originalAvatar": "https://example.com/file.jpg",
  "avatarCropBox": null,
  "name": "レスポンス文字列",
  "email": "response@example.com",
  "authSource": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "company": "レスポンス文字列",
  "invitationCode": "レスポンス文字列",
  "apiKeys": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス例の名前",
      "description": "レスポンス例の説明"
    }
  ],
  "permissions": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス例の名前",
    "description": "レスポンス例の説明"
  },
  "resourcePermissions": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス例の名前",
    "description": "レスポンス例の説明"
  },
  "isOwner": false,
  "maigptCapabilities": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス例の名前",
    "description": "レスポンス例の説明"
  }
}
```

***

### 現在のユーザーの権限を取得 <a href="#permissions-list" id="permissions-list"></a>

GET `/api/v1/permissions/`

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/permissions/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/permissions/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/permissions/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/permissions/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
[
  {
    "id": string (uuid)
    "name": string
    "value": string
    "description": string
    "children": [
      object
    ]
  }
]
```

**レスポンスの値の例**

```json
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列",
    "value": "レスポンス文字列",
    "description": "レスポンス文字列",
    "children": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス例の名前",
        "description": "レスポンス例の説明"
      }
    ]
  }
]
```

***

### 指定した組織のメンバー一覧を取得 <a href="#organizations-members-list" id="organizations-members-list"></a>

GET `/api/v1/organizations/{organizationPk}/members/`

#### パラメータ

| パラメータ名             | 必須 | 型       | 説明                                                                                                                                                                |
| ------------------ | -- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `organizationPk`   | ✅  | string  | A UUID string identifying this organization ID                                                                                                                    |
| `group`            | ❌  | string  |                                                                                                                                                                   |
| `ids`              | ❌  | string  |                                                                                                                                                                   |
| `inbox`            | ❌  | string  |                                                                                                                                                                   |
| `isActive`         | ❌  | boolean |                                                                                                                                                                   |
| `page`             | ❌  | integer | A page number within the paginated result set.                                                                                                                    |
| `pageSize`         | ❌  | integer | Number of results to return per page.                                                                                                                             |
| `pagination`       | ❌  | string  | ページネーションを行うかどうか (true/false)                                                                                                                                      |
| `query`            | ❌  | string  |                                                                                                                                                                   |
| `search`           | ❌  | string  |                                                                                                                                                                   |
| `withGroupSources` | ❌  | boolean | true の場合、\`groups\` は各ロールを一度だけ列挙し、あわせて \`sources\`（そのロールが割り当てられた方法：manual／ldap／scim／eip／cloudflare\_access。重複を除いてソート済み。デフォルトロールは空配列）を返します。ページネーション付きの一覧のみ対応しています。 |

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/?group=550e8400-e29b-41d4-a716-446655440000&ids=example&inbox=550e8400-e29b-41d4-a716-446655440000&isActive=true&page=1&pageSize=1&pagination=example&query=example&search=example&withGroupSources=true" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/?group=550e8400-e29b-41d4-a716-446655440000&ids=example&inbox=550e8400-e29b-41d4-a716-446655440000&isActive=true&page=1&pageSize=1&pagination=example&query=example&search=example&withGroupSources=true", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/?group=550e8400-e29b-41d4-a716-446655440000&ids=example&inbox=550e8400-e29b-41d4-a716-446655440000&isActive=true&page=1&pageSize=1&pagination=example&query=example&search=example&withGroupSources=true"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/?group=550e8400-e29b-41d4-a716-446655440000&ids=example&inbox=550e8400-e29b-41d4-a716-446655440000&isActive=true&page=1&pageSize=1&pagination=example&query=example&search=example&withGroupSources=true", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string (uuid)
      "name": string
      "displayName": string // Name set by the organization owner for this organization only; empty string when not set (``name`` then falls back to the account name).
      "accountName": string // Account name of the member (shared across organizations); shown when display name is cleared.
      "isScimManaged": boolean // True when the member is provisioned by SCIM; the identity provider manages the member and the organization name cannot be changed manually.
      "email": string
      "isActive": boolean
      "isOwner": boolean // メンバーが組織のオーナーかどうかを確認します（OWNER Group を通じて）

キャッシュを使用して、同一リクエスト内での重複クエリを避けます
キャッシュの有効期間：member インスタンスが存在する間有効です

重複クエリを避けるため、annotation の結果がある場合はそれを優先して使用します
      "permissions": [ // Compute the permission tree once per (organization, custom-group set) per request.

The tree depends only on the member's organization (default groups, feature
flags, plan whitelist), the member's custom groups, and the global ``Config``,
so members sharing a group set get the same result. A large role's
``pagination=false`` listing otherwise recomputes it per row — one Redis
``Config`` fetch plus the permission walk each time (issue #8436; the largest
prod role has 3,837 members and a single group set). The memo lives in the
serializer context, so it never outlives the request. Rows without the eager
loaded ``_custom_groups_cache`` (single-object paths) keep computing directly.
        object
      ]
      "groups": [
        object
      ]
      "creditQuotaRequired"?: boolean // When True, member must have an active quota to consume credits (任意)
      "activeQuota": object // Return the most recent quota summary (active first), via prefetch to avoid N+1.
      "metadata": object // Organization-scoped member attributes, injected into LLM system prompt
      "availabilityStatus":  // Self-declared availability for auto-assignment. Paused members are skipped by the dispatch engine but can still be manually assigned or claim conversations. Not touched by SCIM provisioning.

* `available` - Available
* `paused` - Paused
      {
      }
      "createdAt": string (timestamp)
    }
  ]
}
```

**レスポンスのサンプル値**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス文字列",
      "displayName": "レスポンス文字列",
      "accountName": "レスポンス文字列",
      "isScimManaged": false,
      "email": "レスポンス文字列",
      "isActive": false,
      "isOwner": false,
      "permissions": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "レスポンスのサンプル名",
          "description": "レスポンスのサンプル説明"
        }
      ],
      "groups": [
        {
          "id": "550e8400-e29b-41d4-a716-446655440000",
          "name": "レスポンスのサンプル名",
          "description": "レスポンスのサンプル説明"
        }
      ],
      "creditQuotaRequired": false,
      "activeQuota": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンスのサンプル名",
        "description": "レスポンスのサンプル説明"
      },
      "metadata": null,
      "availabilityStatus": {},
      "createdAt": "レスポンス文字列"
    }
  ]
}
```

***

### 特定のメンバーの詳細情報を取得 <a href="#organizations-members-retrieve" id="organizations-members-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/members/{id}/`

#### パラメータ

| パラメータ名           | 必須 | 型      | 説明                                             |
| ---------------- | -- | ------ | ---------------------------------------------- |
| `id`             | ✅  | string | A UUID string identifying this member.         |
| `organizationPk` | ✅  | string | A UUID string identifying this organization ID |

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "name": string
  "displayName": string // Name set by the organization owner for this organization only; empty string when not set (``name`` then falls back to the account name).
  "accountName": string // Account name of the member (shared across organizations); shown when display name is cleared.
  "isScimManaged": boolean // True when the member is provisioned by SCIM; the identity provider manages the member and the organization name cannot be changed manually.
  "email": string
  "isActive": boolean
  "isOwner": boolean // メンバーが組織のオーナーかどうかを確認します（OWNER Group を通じて）

キャッシュを使用して、同一リクエスト内での重複クエリを避けます
キャッシュの有効期間：member インスタンスが存在する間有効です

重複クエリを避けるため、annotation の結果がある場合はそれを優先して使用します
  "permissions": [ // Compute the permission tree once per (organization, custom-group set) per request.

The tree depends only on the member's organization (default groups, feature
flags, plan whitelist), the member's custom groups, and the global ``Config``,
so members sharing a group set get the same result. A large role's
``pagination=false`` listing otherwise recomputes it per row — one Redis
``Config`` fetch plus the permission walk each time (issue #8436; the largest
prod role has 3,837 members and a single group set). The memo lives in the
serializer context, so it never outlives the request. Rows without the eager
loaded ``_custom_groups_cache`` (single-object paths) keep computing directly.
    object
  ]
  "groups": [
    object
  ]
  "creditQuotaRequired"?: boolean // When True, member must have an active quota to consume credits (任意)
  "activeQuota": object // Return the most recent quota summary (active first), via prefetch to avoid N+1.
  "metadata": object // Organization-scoped member attributes, injected into LLM system prompt
  "availabilityStatus":  // Self-declared availability for auto-assignment. Paused members are skipped by the dispatch engine but can still be manually assigned or claim conversations. Not touched by SCIM provisioning.

* `available` - Available
* `paused` - Paused
  {
  }
  "createdAt": string (timestamp)
}
```

**レスポンスのサンプル値**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "displayName": "レスポンス文字列",
  "accountName": "レスポンス文字列",
  "isScimManaged": false,
  "email": "レスポンス文字列",
  "isActive": false,
  "isOwner": false,
  "permissions": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンスのサンプル名",
      "description": "レスポンスのサンプル説明"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンスのサンプル名",
      "description": "レスポンスのサンプル説明"
    }
  ],
  "creditQuotaRequired": false,
  "activeQuota": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンスのサンプル名",
    "description": "レスポンスのサンプル説明"
  },
  "metadata": null,
  "availabilityStatus": {},
  "createdAt": "レスポンス文字列"
}
```

***

### 組織情報を更新 <a href="#organizations-update" id="organizations-update"></a>

PUT `/api/v1/organizations/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                                           |
| ------ | -- | ------ | -------------------------------------------- |
| `id`   | ✅  | string | A UUID string identifying this organization. |

#### リクエスト内容

**リクエストパラメータ**

| フィールド                          | 型            | 必須  | 説明                                                                                                                                                                                                          |
| ------------------------------ | ------------ | --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name                           | string       | はい  |                                                                                                                                                                                                             |
| compactLogo                    | string (uri) | いいえ |                                                                                                                                                                                                             |
| fullLogo                       | string (uri) | いいえ |                                                                                                                                                                                                             |
| themePrimaryColor              | object       | いいえ | UI テーマカラー。ボタンやリンクなどの要素の色に使用します（HEX 形式、例：#0960bd）。空欄の場合は未設定を意味し、フロントエンドはシステムのブランドカラーにフォールバックします                                                                                                              |
| hideChinaModels                | boolean      | いいえ | When on, platform models whose developer is based in China (including ones added later) cannot be used in this organization: model menus, assistants, the API and AI Gateway exclude them, and live tran... |
| autoActivateNewChatbotChannels | boolean      | いいえ | Initial state of the web chat and API channels of a new chatbot whose creator did not set them (duplicates, templates and API calls without the values included). When on, they start active; when off (... |
| companyName                    | string       | いいえ | Applicant-reported company name collected at organization creation for approval review.                                                                                                                     |
| taxId                          | object       | いいえ | Applicant-reported business tax ID (8 digits, optional). Stored as-is; not verified.                                                                                                                        |
| contactPhone                   | string       | いいえ | Applicant-reported contact phone collected at organization creation for approval review.                                                                                                                    |
| applicationMetadata            | object       | いいえ | Extra applicant-reported key-value fields collected at organization creation. Lets the frontend collect additional review fields without a schema migration; the core review fields (company name, tax I... |
| invitationCode                 | string       | いいえ |                                                                                                                                                                                                             |

**リクエストスキーマの例**

```typescript
{
  "name": string
  "compactLogo"?: string (uri) // 任意
  "fullLogo"?: string (uri) // 任意
  "themePrimaryColor"?: // 複数の型を取りうる (任意)
  string // UI テーマカラー。ボタンやリンクなどの要素の色に使用します（HEX 形式、例：#0960bd）。空欄の場合は未設定を意味し、フロントエンドはシステムのブランドカラーにフォールバックします (任意)
  "hideChinaModels"?: boolean // When on, platform models whose developer is based in China (including ones added later) cannot be used in this organization: model menus, assistants, the API and AI Gateway exclude them, and live transcription lists China-developed speech engines as unavailable. Off by default; turn it on for public-sector or other organizations that must not use them. (任意)
  "autoActivateNewChatbotChannels"?: boolean // Initial state of the web chat and API channels of a new chatbot whose creator did not set them (duplicates, templates and API calls without the values included). When on, they start active; when off (the platform default), they start inactive until a member turns them on. The creator can still override both channels in the New Chatbot dialog or the create API. The backstage (admin) channel is always active. Changing this does not affect existing chatbots. (任意)
  "companyName"?: string // Applicant-reported company name collected at organization creation for approval review. (任意)
  "taxId"?: // 複数の型を取りうる (任意)
  string // Applicant-reported business tax ID (8 digits, optional). Stored as-is; not verified. (任意)
  "contactPhone"?: string // Applicant-reported contact phone collected at organization creation for approval review. (任意)
  "applicationMetadata"?: object // Extra applicant-reported key-value fields collected at organization creation. Lets the frontend collect additional review fields without a schema migration; the core review fields (company name, tax ID, contact phone) stay as named columns. (任意)
  "invitationCode"?: string // 任意
}
```

**リクエストのサンプル値**

```json
{
  "id": "5b01e0b9-0b0e-4079-8150-d12015576d2c",
  "name": "Updated Org Name",
  "created_at": "1748336288000",
  "usage_statistics": {
    "chatbots_count": 0,
    "countable_chatbots_count": 0,
    "exempt_chatbots_by_mode": {},
    "allowed_chatbot_reply_modes": [],
    "can_create_chatbot": true,
    "create_chatbot_limit": 1,
    "current_month_words_count_total": 1000000,
    "current_month_used_words_count_total": 0,
    "current_month_used_conversations_count_total": 0,
    "available_upload_files_size_total": 104857600,
    "used_upload_file_size_total": 0
  },
  "organization_plan": {
    "id": "cac825e8-cb9b-4a16-b440-4ff6b2e73911",
    "plan_name": "無料プラン",
    "expired_at": null
  },
  "is_trial": false,
  "expiration_days": null
}
```

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "5b01e0b9-0b0e-4079-8150-d12015576d2c",
    "name": "Updated Org Name",
    "created_at": "1748336288000",
    "usage_statistics": {
      "chatbots_count": 0,
      "countable_chatbots_count": 0,
      "exempt_chatbots_by_mode": {},
      "allowed_chatbot_reply_modes": [],
      "can_create_chatbot": true,
      "create_chatbot_limit": 1,
      "current_month_words_count_total": 1000000,
      "current_month_used_words_count_total": 0,
      "current_month_used_conversations_count_total": 0,
      "available_upload_files_size_total": 104857600,
      "used_upload_file_size_total": 0
    },
    "organization_plan": {
      "id": "cac825e8-cb9b-4a16-b440-4ff6b2e73911",
      "plan_name": "無料プラン",
      "expired_at": null
    },
    "is_trial": false,
    "expiration_days": null
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエスト内容 (payload)
const data = {
    "id": "5b01e0b9-0b0e-4079-8150-d12015576d2c",
    "name": "Updated Org Name",
    "created_at": "1748336288000",
    "usage_statistics": {
      "chatbots_count": 0,
      "countable_chatbots_count": 0,
      "exempt_chatbots_by_mode": {},
      "allowed_chatbot_reply_modes": [],
      "can_create_chatbot": true,
      "create_chatbot_limit": 1,
      "current_month_words_count_total": 1000000,
      "current_month_used_words_count_total": 0,
      "current_month_used_conversations_count_total": 0,
      "available_upload_files_size_total": 104857600,
      "used_upload_file_size_total": 0
    },
    "organization_plan": {
      "id": "cac825e8-cb9b-4a16-b440-4ff6b2e73911",
      "plan_name": "無料プラン",
      "expired_at": null
    },
    "is_trial": false,
    "expiration_days": null
  };

axios.put("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエスト内容 (payload)
data = {
    "id": "5b01e0b9-0b0e-4079-8150-d12015576d2c",
    "name": "Updated Org Name",
    "created_at": "1748336288000",
    "usage_statistics": {
        "chatbots_count": 0,
        "countable_chatbots_count": 0,
        "exempt_chatbots_by_mode": {},
        "allowed_chatbot_reply_modes": [],
        "can_create_chatbot": True,
        "create_chatbot_limit": 1,
        "current_month_words_count_total": 1000000,
        "current_month_used_words_count_total": 0,
        "current_month_used_conversations_count_total": 0,
        "available_upload_files_size_total": 104857600,
        "used_upload_file_size_total": 0
    },
    "organization_plan": {
        "id": "cac825e8-cb9b-4a16-b440-4ff6b2e73911",
        "plan_name": "無料プラン",
        "expired_at": None
    },
    "is_trial": False,
    "expiration_days": None
}

response = requests.put(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'id' => '5b01e0b9-0b0e-4079-8150-d12015576d2c',
            'name' => 'Updated Org Name',
            'created_at' => '1748336288000',
            'usage_statistics' => [
                'chatbots_count' => 0,
                'countable_chatbots_count' => 0,
                'exempt_chatbots_by_mode' => new \stdClass(),
                'allowed_chatbot_reply_modes' => [],
                'can_create_chatbot' => true,
                'create_chatbot_limit' => 1,
                'current_month_words_count_total' => 1000000,
                'current_month_used_words_count_total' => 0,
                'current_month_used_conversations_count_total' => 0,
                'available_upload_files_size_total' => 104857600,
                'used_upload_file_size_total' => 0
            ],
            'organization_plan' => [
                'id' => 'cac825e8-cb9b-4a16-b440-4ff6b2e73911',
                'plan_name' => '無料プラン',
                'expired_at' => null
            ],
            'is_trial' => false,
            'expiration_days' => null
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンス構造の例**

```typescript
{
  "id": string (uuid) // 組織 ID
  "name": string // 組織名
  "created_at": string (timestamp) // 作成日時のタイムスタンプ
  "usage_statistics": { // 使用状況の統計情報
  {
    "chatbots_count"?: integer // チャットボット数 (省略可)
    "countable_chatbots_count"?: integer // 作成上限にカウントされるチャットボット数（プランの許可リストに含まれないモードはカウントされません） (省略可)
    "exempt_chatbots_by_mode"?: object // 上限にカウントされないチャットボット数です。カウント対象外となるモード別に集計します (省略可)
    "allowed_chatbot_reply_modes"?: [ // プランで作成が許可される応答モードの許可リスト（空の配列は制限なしを意味します） (省略可)
      string
    ]
    "can_create_chatbot"?: boolean // チャットボットを作成できるかどうか (省略可)
    "create_chatbot_limit"?: integer // 作成できるチャットボット数の上限（-1 は無制限、0 は作成禁止を意味します） (省略可)
    "current_month_words_count_total"?: integer // 今月の合計文字数の上限 (省略可)
    "current_month_used_words_count_total"?: integer // 今月の使用済み文字数 (省略可)
    "current_month_used_conversations_count_total"?: integer // 今月の使用済み会話数 (省略可)
    "available_upload_files_size_total"?: integer // アップロード可能なファイルの合計サイズ（バイト） (省略可)
    "used_upload_file_size_total"?: integer // アップロード済みファイルの使用サイズ（バイト） (省略可)
  }
  }
  "organization_plan": { // 組織のプラン情報
  {
    "id"?: string (uuid) // プラン ID (省略可)
    "plan_name"?: string // プラン名 (省略可)
    "expired_at"?: string (date-time) // 有効期限 (省略可)
  }
  }
  "is_trial"?: boolean // 試用期間中かどうかを示します。組織に試用プランが 1 つだけあり、現在有効な場合に true になります (省略可)
  "expiration_days"?: integer // 有効期限が切れてからの日数です。正の数は期限切れからの日数、null は有効期限内または無期限のプランを示します (省略可)
}
```

**レスポンスの値の例**

```json
{
  "id": "5b01e0b9-0b0e-4079-8150-d12015576d2c",
  "name": "Updated Org Name",
  "created_at": "1748336288000",
  "usage_statistics": {
    "chatbots_count": 0,
    "countable_chatbots_count": 0,
    "exempt_chatbots_by_mode": {},
    "allowed_chatbot_reply_modes": [],
    "can_create_chatbot": true,
    "create_chatbot_limit": 1,
    "current_month_words_count_total": 1000000,
    "current_month_used_words_count_total": 0,
    "current_month_used_conversations_count_total": 0,
    "available_upload_files_size_total": 104857600,
    "used_upload_file_size_total": 0
  },
  "organization_plan": {
    "id": "cac825e8-cb9b-4a16-b440-4ff6b2e73911",
    "plan_name": "無料プラン",
    "expired_at": null
  },
  "is_trial": false,
  "expiration_days": null
}
```

***

### 現在のユーザーの詳細情報を更新 <a href="#users-current-update" id="users-current-update"></a>

PUT `/api/v1/users/current/`

#### リクエストボディ

**リクエストパラメータ**

| フィールド          | 型              | 必須  | 説明                                                                                                                       |
| -------------- | -------------- | --- | ------------------------------------------------------------------------------------------------------------------------ |
| avatar         | string (uri)   | いいえ |                                                                                                                          |
| originalAvatar | string (uri)   | いいえ | ユーザーがアップロードしたアバターの元画像（長辺は 2048px 以内に制限）。編集のたびにこの画像から切り直すことで、切り抜き済みの結果をさらに切り抜くことによる劣化の蓄積を防ぎます。この機能のリリース前の既存データは空で、補完されません |
| avatarCropBox  | object         | いいえ | 前回の切り抜き枠の元画像上での位置とサイズ（x/y/width/height、rotate/scale\_x/scale\_y は任意）。座標は保存された元画像を基準とします                                  |
| name           | string         | はい  |                                                                                                                          |
| email          | string (email) | はい  |                                                                                                                          |
| company        | string         | いいえ |                                                                                                                          |
| invitationCode | object         | いいえ |                                                                                                                          |

**リクエストスキーマの例**

```typescript
{
  "avatar"?: string (uri) // 任意
  "originalAvatar"?: string (uri) // ユーザーがアップロードしたアバターの元画像（長辺は 2048px 以内に制限）。編集のたびにこの画像から再度切り抜くため、切り抜き結果をさらに切り抜くことによる劣化の蓄積を防げます。この機能の提供開始前の既存データは空で、補完されません (任意)
  "avatarCropBox"?: object // 前回の切り抜きボックスの元画像上での位置とサイズ（x/y/width/height、任意で rotate/scale_x/scale_y）。座標は保存された元画像を基準とします (任意)
  "name": string
  "email": string (email)
  "company"?: string // 任意
  "invitationCode"?: // 複数の型の可能性があります (任意)
  string // 任意
}
```

**リクエストの値の例**

```json
{
  "avatar": "https://example.com/file.jpg",
  "originalAvatar": "https://example.com/file.jpg",
  "avatarCropBox": null,
  "name": "サンプル名",
  "email": "user@example.com",
  "company": "サンプル文字列",
  "invitationCode": null
}
```

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X PUT "https://api.maiagent.ai/api/v1/users/current/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// FormData オブジェクトを作成
const formData = new FormData();
// フォームフィールドを追加

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    ...formData.getHeaders()
  }
};

axios.put("https://api.maiagent.ai/api/v1/users/current/", formData, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/users/current/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}

# ファイルとフォームデータを作成
files = {
    'file': ('example.pdf', open('example.pdf', 'rb'), 'application/pdf')
}

response = requests.put(url, files=files, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->put("https://api.maiagent.ai/api/v1/users/current/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ],
        'multipart' => [
            [
                'name' => 'file',
                'contents' => fopen('example.pdf', 'r'),
                'filename' => 'example.pdf'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "avatar"?: string (uri) // 任意
  "originalAvatar"?: string (uri) // ユーザーがアップロードしたアバターの元画像（長辺は 2048px 以内に制限）。編集のたびにこの画像から再度切り抜くため、切り抜き結果をさらに切り抜くことによる劣化の蓄積を防げます。この機能の提供開始前の既存データは空で、補完されません (任意)
  "avatarCropBox"?: object // 前回の切り抜きボックスの元画像上での位置とサイズ（x/y/width/height、任意で rotate/scale_x/scale_y）。座標は保存された元画像を基準とします (任意)
  "name": string
  "email": string (email)
  "authSource": 
  {
    "id": string (uuid)
    "name": string
  }
  "company"?: string // 任意
  "invitationCode"?: // 複数の型の可能性があります (任意)
  string // 任意
  "apiKeys": [ // 指定した組織におけるユーザーの API キー一覧を取得します。

処理の流れ：
1. リクエストから現在の組織インスタンスを取得する
2. 組織インスタンスがない場合（通常はサードパーティ SSO ログイン時）、ユーザーの認証ソースを使って
   その認証ソースのデフォルト組織（is_auth_source_default_organization=True）を検索する

注意：
- サードパーティ SSO ログイン時、リクエストには organization_instance が含まれません
- auth_source と is_auth_source_default_organization のフラグを使って組織を特定する必要があります
    object
  ]
  "permissions": object // 現在の組織におけるユーザーの権限を取得します（親子のネスト構造）。
  "resourcePermissions": object // 現在の組織におけるユーザーのリソース作成権限を取得します。
  "isOwner": boolean // 現在の組織でユーザーが Owner かどうかを判定します。
  "maigptCapabilities": object // メンバーが MaiGPT で利用できる有効な組み込み機能の権限（ロール権限の解決結果）。フロントエンドでの表示／非表示に使用します。

member context がない場合（組織に紐付いていない場合）、解決結果はすべて有効になります。これは resolver の「データ欠落時にロックしない」
方針と一致します。フロントエンドでの非表示は UX 上の措置にすぎず、正式なチェックは返信経路の gate で行われます。
}
```

**レスポンスの値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "avatar": "https://example.com/file.jpg",
  "originalAvatar": "https://example.com/file.jpg",
  "avatarCropBox": null,
  "name": "レスポンス文字列",
  "email": "response@example.com",
  "authSource": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス文字列"
  },
  "company": "レスポンス文字列",
  "invitationCode": "レスポンス文字列",
  "apiKeys": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス例の名前",
      "description": "レスポンス例の説明"
    }
  ],
  "permissions": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス例の名前",
    "description": "レスポンス例の説明"
  },
  "resourcePermissions": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス例の名前",
    "description": "レスポンス例の説明"
  },
  "isOwner": false,
  "maigptCapabilities": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンス例の名前",
    "description": "レスポンス例の説明"
  }
}
```

***

### メンバーのロールを更新 <a href="#organizations-members-update-groups-create" id="organizations-members-update-groups-create"></a>

POST `/api/v1/organizations/{organizationPk}/members/{id}/update-groups/`

#### パラメータ

| パラメータ名           | 必須 | 型      | 説明                                             |
| ---------------- | -- | ------ | ---------------------------------------------- |
| `id`             | ✅  | string | A UUID string identifying this member.         |
| `organizationPk` | ✅  | string | A UUID string identifying this organization ID |

#### リクエストボディ

**リクエストパラメータ**

| フィールド  | 型              | 必須 | 説明 |
| ------ | -------------- | -- | -- |
| groups | array\[string] | はい |    |

**リクエストスキーマ例**

```typescript
{
  "groups": [
    string (uuid)
  ]
}
```

**リクエストのサンプル値**

```json
{
  "groups": [
    "4e368ab4-c543-48a2-bbb8-f6f5a0bf6c61",
    "5f479bc5-d654-59b3-ccc9-g7g6b1cg7d72"
  ]
}
```

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/update-groups/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "groups": [
      "4e368ab4-c543-48a2-bbb8-f6f5a0bf6c61",
      "5f479bc5-d654-59b3-ccc9-g7g6b1cg7d72"
    ]
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "groups": [
      "4e368ab4-c543-48a2-bbb8-f6f5a0bf6c61",
      "5f479bc5-d654-59b3-ccc9-g7g6b1cg7d72"
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/update-groups/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "groups": [
        "4e368ab4-c543-48a2-bbb8-f6f5a0bf6c61",
        "5f479bc5-d654-59b3-ccc9-g7g6b1cg7d72"
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/update-groups/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'groups' => [
                '4e368ab4-c543-48a2-bbb8-f6f5a0bf6c61',
                '5f479bc5-d654-59b3-ccc9-g7g6b1cg7d72'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマ例**

```typescript
{
  "id": string (uuid)
  "name": string
  "displayName": string // Name set by the organization owner for this organization only; empty string when not set (``name`` then falls back to the account name).
  "accountName": string // Account name of the member (shared across organizations); shown when display name is cleared.
  "isScimManaged": boolean // True when the member is provisioned by SCIM; the identity provider manages the member and the organization name cannot be changed manually.
  "email": string
  "isActive": boolean
  "isOwner": boolean // メンバーが組織のオーナーかどうかを確認します（OWNER Group 経由）

キャッシュを使用して、同一リクエスト内での重複クエリを防ぎます
キャッシュの有効期間：メンバーインスタンスが存在する間は有効です

アノテーションの結果がある場合は優先的に使用し、重複クエリを防ぎます
  "permissions": [ // Compute the permission tree once per (organization, custom-group set) per request.

The tree depends only on the member's organization (default groups, feature
flags, plan whitelist), the member's custom groups, and the global ``Config``,
so members sharing a group set get the same result. A large role's
``pagination=false`` listing otherwise recomputes it per row — one Redis
``Config`` fetch plus the permission walk each time (issue #8436; the largest
prod role has 3,837 members and a single group set). The memo lives in the
serializer context, so it never outlives the request. Rows without the eager
loaded ``_custom_groups_cache`` (single-object paths) keep computing directly.
    object
  ]
  "groups": [
    object
  ]
  "creditQuotaRequired"?: boolean // When True, member must have an active quota to consume credits (任意)
  "activeQuota": object // Return the most recent quota summary (active first), via prefetch to avoid N+1.
  "metadata": object // Organization-scoped member attributes, injected into LLM system prompt
  "availabilityStatus":  // Self-declared availability for auto-assignment. Paused members are skipped by the dispatch engine but can still be manually assigned or claim conversations. Not touched by SCIM provisioning.

* `available` - Available
* `paused` - Paused
  {
  }
  "createdAt": string (timestamp)
}
```

**レスポンスのサンプル値**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "displayName": "レスポンス文字列",
  "accountName": "レスポンス文字列",
  "isScimManaged": false,
  "email": "レスポンス文字列",
  "isActive": false,
  "isOwner": false,
  "permissions": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンスのサンプル名",
      "description": "レスポンスのサンプル説明"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンスのサンプル名",
      "description": "レスポンスのサンプル説明"
    }
  ],
  "creditQuotaRequired": false,
  "activeQuota": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンスのサンプル名",
    "description": "レスポンスのサンプル説明"
  },
  "metadata": null,
  "availabilityStatus": {},
  "createdAt": "レスポンス文字列"
}
```

**ステータスコード: 400**

**レスポンススキーマ例**

```typescript
object
```

***

### メンバー名を変更 <a href="#organizations-members-display-name-partial-update" id="organizations-members-display-name-partial-update"></a>

PATCH `/api/v1/organizations/{organizationPk}/members/{id}/display-name/`

{% hint style="info" %}
**必要な権限**：組織オーナーのみが呼び出せます。メンバー管理権限があっても、オーナー以外には `403` が返されます。この組織内で表示されるメンバー名（組織内の名前）のみを変更します。アカウント名や、メンバーが所属する他の組織には影響しません。ロール、クォータ、カスタム属性など、その他のメンバー情報も変更されません。`displayName` の前後の空白は除去され、最大 255 文字まで指定できます。一意である必要はありません。空文字列または空白のみを渡すと設定が解除され、アカウント名（`accountName`）が表示されます。現在の表示名（`name`。組織内の名前が未設定の場合はアカウント名）と同じ場合は変更なしとみなされ、書き込みもアクティビティログへの記録も行われず、`200` が返されます。SCIM で同期管理されているメンバー（`isScimManaged` が `true`）には `400` が返されます。ID プロバイダー側で変更してください。メンバーがこの組織に属していない場合は `404` が返されます。成功時は「特定のメンバーの詳細情報を取得」と同じメンバーオブジェクトが返され、`name` に新しい表示名が入ります。実際に変更された場合は、組織のアクティビティログに記録されます。
{% endhint %}

#### パラメータ

| パラメータ名           | 必須 | 型      | 説明                        |
| ---------------- | -- | ------ | ------------------------- |
| `id`             | ✅  | string | このメンバーを識別する UUID 文字列です。   |
| `organizationPk` | ✅  | string | この組織 ID を識別する UUID 文字列です。 |

#### リクエストボディ

**リクエストパラメータ**

| フィールド       | 型      | 必須 | 説明                                                                                                                                                                   |
| ----------- | ------ | -- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| displayName | string | はい | New name of the member in this organization. Leading/trailing whitespace is trimmed; an empty or whitespace-only value clears it so the account name is shown again. |

**リクエストスキーマの例**

```typescript
{
  "displayName": string // New name of the member in this organization. Leading/trailing whitespace is trimmed; an empty or whitespace-only value clears it so the account name is shown again.
}
```

**リクエスト値の例**

```json
{
  "displayName": "文字列の例"
}
```

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/display-name/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "displayName": "文字列の例"
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "displayName": "文字列の例"
  };

axios.patch("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/display-name/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "displayName": "文字列の例"
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/display-name/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'displayName' => '文字列の例'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "name": string
  "displayName": string // Name set by the organization owner for this organization only; empty string when not set (``name`` then falls back to the account name).
  "accountName": string // Account name of the member (shared across organizations); shown when display name is cleared.
  "isScimManaged": boolean // True when the member is provisioned by SCIM; the identity provider manages the member and the organization name cannot be changed manually.
  "email": string
  "isActive": boolean
  "isOwner": boolean // メンバーが組織オーナーかどうかを確認します（OWNER Group 経由）

キャッシュを使用して、同一リクエスト内での重複クエリを防ぎます
キャッシュの有効期間：メンバーインスタンスの存続期間中です

アノテーションの結果がある場合は優先的に使用し、重複クエリを防ぎます
  "permissions": [ // Compute the permission tree once per (organization, custom-group set) per request.

The tree depends only on the member's organization (default groups, feature
flags, plan whitelist), the member's custom groups, and the global ``Config``,
so members sharing a group set get the same result. A large role's
``pagination=false`` listing otherwise recomputes it per row — one Redis
``Config`` fetch plus the permission walk each time (issue #8436; the largest
prod role has 3,837 members and a single group set). The memo lives in the
serializer context, so it never outlives the request. Rows without the eager
loaded ``_custom_groups_cache`` (single-object paths) keep computing directly.
    object
  ]
  "groups": [
    object
  ]
  "creditQuotaRequired"?: boolean // When True, member must have an active quota to consume credits (任意)
  "activeQuota": object // Return the most recent quota summary (active first), via prefetch to avoid N+1.
  "metadata": object // Organization-scoped member attributes, injected into LLM system prompt
  "availabilityStatus":  // Self-declared availability for auto-assignment. Paused members are skipped by the dispatch engine but can still be manually assigned or claim conversations. Not touched by SCIM provisioning.

* `available` - Available
* `paused` - Paused
  {
  }
  "createdAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "displayName": "レスポンス文字列",
  "accountName": "レスポンス文字列",
  "isScimManaged": false,
  "email": "レスポンス文字列",
  "isActive": false,
  "isOwner": false,
  "permissions": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンスの名前の例",
      "description": "レスポンスの説明の例"
    }
  ],
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンスの名前の例",
      "description": "レスポンスの説明の例"
    }
  ],
  "creditQuotaRequired": false,
  "activeQuota": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンスの名前の例",
    "description": "レスポンスの説明の例"
  },
  "metadata": null,
  "availabilityStatus": {},
  "createdAt": "レスポンス文字列"
}
```

**ステータスコード: 400 - メンバーが SCIM で同期管理されている、名前が 255 文字を超えている、または displayName が指定されていません**

**レスポンススキーマの例**

```typescript
{
  "displayName"?: [ // エラーの原因：メンバーが SCIM で同期管理されている、名前が 255 文字を超えている、または displayName が指定されていません (任意)
    string
  ]
}
```

**レスポンス値の例**

```json
{
  "displayName": [
    "このメンバーの名前は ID プロバイダー（SCIM）で同期管理されているため、手動で変更できません"
  ]
}
```

**ステータスコード: 403 - 呼び出し元が組織オーナーではありません**

**レスポンススキーマの例**

```typescript
{
  "detail"?: string // 任意
}
```

**レスポンス値の例**

```json
{
  "detail": "組織オーナーのみが名前を変更できます"
}
```

**ステータスコード: 404 - メンバーが存在しないか、この組織に所属していません**

***

### メンバーを組織に招待 <a href="#auth-unified-invitations-create" id="auth-unified-invitations-create"></a>

POST `/api/v1/auth/unified-invitations/`

{% hint style="info" %}
API Key が所属する組織が対象です。「組織概要権限」が必要です（組織オーナーにはこの制限はありません）。`emails` は 1 回につき最大 100 件まで指定できます。登録済みのユーザーは直接メンバーになり（レスポンスの `members`）、未登録のメールアドレスには招待メールが送信され、登録後に参加します（レスポンスの `mailInvitations`）。すでにメンバーの場合は `skippedEmails` に含まれます。`groups` は参加後のロールを `[{"id": "ロール ID"}]` 形式で指定します。`creditQuota` を指定すると、今回の招待対象者の個人クォータを事前設定でき、参加時に割り当てられます。指定項目は `quotaLimit`（必須）、`validUntil`（任意。`2026-12-31T23:59:59+08:00` などの ISO 8601 文字列、または 13 桁のミリ秒タイムスタンプで、文字列と数値のいずれも使用可能です。タイムゾーン未指定時は台湾時間として扱われます。現在より後の日時が必要で、省略すると無期限になります）、`resetPeriod`（`none`／`daily`／`weekly`／`monthly`、デフォルトは `none`）、`note`（任意）です。`creditQuota` を指定するには、さらに「Credit 管理権限」が必要で、組織が Credit 課金方式を使用している必要があります。省略した場合は、[新規メンバーのデフォルトクォータ](https://docs.maiagent.ai/api/api-reference/credit#credit-wallets-new-member-quota-policy-retrieve)が有効であれば適用されます。
{% endhint %}

#### リクエストボディ

**リクエストパラメータ**

| フィールド                   | 型                                                               | 必須  | 説明                                                                    |
| ----------------------- | --------------------------------------------------------------- | --- | --------------------------------------------------------------------- |
| creditQuota             | object (4 個のプロパティを含みます: quotaLimit, validUntil, resetPeriod...) | いいえ | Optional credit quota allocated to the invitee when they join.        |
| creditQuota.quotaLimit  | string (decimal)                                                | はい  |                                                                       |
| creditQuota.validUntil  | object                                                          | いいえ | ISO 8601 date-time or 13-digit epoch milliseconds (string or number). |
| creditQuota.resetPeriod | object                                                          | いいえ |                                                                       |
| creditQuota.note        | string                                                          | いいえ |                                                                       |
| groups                  | array\[IdName]                                                  | いいえ |                                                                       |
| emails                  | array\[string]                                                  | はい  | Email address list to invite. Up to 100 emails.                       |

**リクエストスキーマの例**

```typescript
{
  "creditQuota"?:  // Optional credit quota allocated to the invitee when they join. (任意)
  {
    "quotaLimit": string (decimal)
    "validUntil"?: // 異なる型を取る可能性があります (任意)
    string (date-time) // ISO 8601 date-time or 13-digit epoch milliseconds (string or number). (任意)
    "resetPeriod"?:  // 任意
    {
    }
    "note"?: string // 任意
  }
  "groups"?: [ // 任意
    {
      "id": string (uuid)
    }
  ]
  "emails": [ // Email address list to invite. Up to 100 emails.
    string (email)
  ]
}
```

**リクエスト値の例**

```json
{
  "emails": [
    "user@example.com",
    "user2@example.com"
  ],
  "groups": [
    {
      "id": "12345678-1234-5678-1234-567812345678"
    }
  ]
}
```

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/auth/unified-invitations/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "emails": [
      "user@example.com",
      "user2@example.com"
    ],
    "groups": [
      {
        "id": "12345678-1234-5678-1234-567812345678"
      }
    ]
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "emails": [
      "user@example.com",
      "user2@example.com"
    ],
    "groups": [
      {
        "id": "12345678-1234-5678-1234-567812345678"
      }
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/auth/unified-invitations/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "emails": [
        "user@example.com",
        "user2@example.com"
    ],
    "groups": [
        {
            "id": "12345678-1234-5678-1234-567812345678"
        }
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/auth/unified-invitations/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'emails' => [
                'user@example.com',
                'user2@example.com'
            ],
            'groups' => [
                [
                    'id' => '12345678-1234-5678-1234-567812345678'
                ]
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "members": [
    {
      "id": string (uuid)
      "email": string (email)
      "name": string
    }
  ]
  "mailInvitations": [
    {
      "creditQuota": 
      {
        "quotaLimit": string (decimal)
        "validUntil": string (date-time)
        "resetPeriod": 
        {
        }
        "note": string
      }
      "creditQuotaSource": string
      "id": string (uuid)
      "email": string (email)
      "displayStatus": string
      "code": string
      "inviter": string (uuid)
      "organization"?: string (uuid) // 任意
      "groups"?: [ // 任意
        {
          "id": string (uuid)
          "name": string
        }
      ]
      "createdAt"?: string (timestamp) // 任意
      "acceptedAt"?: string (timestamp) // 任意
      "lastSentAt": string (timestamp)
      "failureReason": string
      "retryCount": integer
      "canResend": boolean
    }
  ]
  "skippedEmails": [
    string (email)
  ]
}
```

**レスポンス値の例**

```json
{
  "members": [
    {
      "id": "33333333-3333-3333-3333-333333333333",
      "email": "user2@example.com",
      "name": "User Two"
    }
  ],
  "mailInvitations": [
    {
      "id": "87654321-4321-8765-4321-876543210000",
      "email": "user@example.com",
      "displayStatus": "pending",
      "creditQuota": {
        "quotaLimit": "500.000000",
        "validUntil": "2026-12-31T15:59:59+00:00",
        "resetPeriod": "monthly",
        "note": "新入社員用クォータ"
      },
      "creditQuotaSource": "invitation_override"
    }
  ],
  "skippedEmails": []
}
```

**ステータスコード: 400 - リクエストボディが不正です。例えば、メールアドレスの形式が不正、ロールが存在しない、\`creditQuota.validUntil\` の形式が不正または期限切れ、あるいは Credit 課金方式ではない組織に \`creditQuota\` が指定されています**

**ステータスコード: 403 - 組織概要権限がない、Credit 管理権限なしで \`creditQuota\` を指定した、または組織オーナー以外がオーナーロールを指定したか、オーナーロール付きの承諾待ちの招待を再招待しています**

***

### 組織の招待メール履歴を一覧取得 <a href="#auth-organization-mail-invitations-list" id="auth-organization-mail-invitations-list"></a>

GET `/api/v1/auth/organization-mail-invitations/`

{% hint style="info" %}
招待メールの送信状況と承諾状況を照会します。`status` パラメータで絞り込みができ、複数指定も可能です（例：`status=pending&status=mail_failed`）。省略するとすべてのステータスが返されます。`pagination=false` でページネーションを無効にします。「組織概要権限」がある場合は組織全体の招待を確認できますが、オーナーロールを指定した招待は組織オーナーのみが確認できます。それ以外の場合は、自分が送信した招待のみが表示されます。
{% endhint %}

#### パラメータ

| パラメータ名       | 必須 | 型       | 説明                                                                             |
| ------------ | -- | ------- | ------------------------------------------------------------------------------ |
| `pagination` | ❌  | boolean | ページネーションを使用するかどうかです                                                            |
| `status`     | ❌  | string  | 招待ステータスです。複数指定が可能です（例：status=pending\&status=mail\_failed）。省略するとすべてのステータスを返します |

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/auth/organization-mail-invitations/?pagination=true&status=accepted" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/auth/organization-mail-invitations/?pagination=true&status=accepted", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/auth/organization-mail-invitations/?pagination=true&status=accepted"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/auth/organization-mail-invitations/?pagination=true&status=accepted", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
[
  {
    "creditQuota": 
    {
      "quotaLimit": string (decimal)
      "validUntil": string (date-time)
      "resetPeriod": 
      {
      }
      "note": string
    }
    "creditQuotaSource": string
    "id": string (uuid)
    "email": string (email)
    "displayStatus": string
    "code": string
    "inviter": string (uuid)
    "organization"?: string (uuid) // 任意
    "groups"?: [ // 任意
      {
        "id": string (uuid)
        "name": string
      }
    ]
    "createdAt"?: string (timestamp) // 任意
    "acceptedAt"?: string (timestamp) // 任意
    "lastSentAt": string (timestamp)
    "failureReason": string
    "retryCount": integer
    "canResend": boolean
  }
]
```

**レスポンス値の例**

```json
[
  {
    "creditQuota": {
      "quotaLimit": "レスポンス文字列",
      "validUntil": "2026-12-31T23:59:59+08:00",
      "resetPeriod": {},
      "note": "レスポンス文字列"
    },
    "creditQuotaSource": "レスポンス文字列",
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "email": "response@example.com",
    "displayStatus": "レスポンス文字列",
    "code": "レスポンス文字列",
    "inviter": "550e8400-e29b-41d4-a716-446655440000",
    "organization": "550e8400-e29b-41d4-a716-446655440000",
    "groups": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンス文字列"
      }
    ],
    "createdAt": "レスポンス文字列",
    "acceptedAt": "レスポンス文字列",
    "lastSentAt": "レスポンス文字列",
    "failureReason": "レスポンス文字列",
    "retryCount": 456,
    "canResend": false
  }
]
```

***

### 組織の招待メールを再送 <a href="#auth-organization-mail-invitations-resend-create" id="auth-organization-mail-invitations-resend-create"></a>

POST `/api/v1/auth/organization-mail-invitations/{id}/resend/`

{% hint style="info" %}
「組織概要権限」が必要です。リクエストボディは不要です。承諾待ち、または送信に失敗した招待のみ再送できます（承諾済み・取り消し済みの場合は `400` が返されます）。再送は最大 3 回までで、各再送の間隔は 5 分以上必要です。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明 |
| ------ | -- | ------ | -- |
| `id`   | ✅  | string |    |

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/auth/organization-mail-invitations/550e8400-e29b-41d4-a716-446655440000/resend/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエストボディ (payload)
const data = null;

axios.post("https://api.maiagent.ai/api/v1/auth/organization-mail-invitations/550e8400-e29b-41d4-a716-446655440000/resend/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/auth/organization-mail-invitations/550e8400-e29b-41d4-a716-446655440000/resend/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.post(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/auth/organization-mail-invitations/550e8400-e29b-41d4-a716-446655440000/resend/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "creditQuota": 
  {
    "quotaLimit": string (decimal)
    "validUntil": string (date-time)
    "resetPeriod": 
    {
    }
    "note": string
  }
  "creditQuotaSource": string
  "id": string (uuid)
  "email": string (email)
  "displayStatus": string
  "code": string
  "inviter": string (uuid)
  "organization"?: string (uuid) // 任意
  "groups"?: [ // 任意
    {
      "id": string (uuid)
      "name": string
    }
  ]
  "createdAt"?: string (timestamp) // 任意
  "acceptedAt"?: string (timestamp) // 任意
  "lastSentAt": string (timestamp)
  "failureReason": string
  "retryCount": integer
  "canResend": boolean
}
```

**レスポンス値の例**

```json
{
  "creditQuota": {
    "quotaLimit": "レスポンス文字列",
    "validUntil": "2026-12-31T23:59:59+08:00",
    "resetPeriod": {},
    "note": "レスポンス文字列"
  },
  "creditQuotaSource": "レスポンス文字列",
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "email": "response@example.com",
  "displayStatus": "レスポンス文字列",
  "code": "レスポンス文字列",
  "inviter": "550e8400-e29b-41d4-a716-446655440000",
  "organization": "550e8400-e29b-41d4-a716-446655440000",
  "groups": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス文字列"
    }
  ],
  "createdAt": "レスポンス文字列",
  "acceptedAt": "レスポンス文字列",
  "lastSentAt": "レスポンス文字列",
  "failureReason": "レスポンス文字列",
  "retryCount": 456,
  "canResend": false
}
```

***

### 組織の API Key 一覧を取得 <a href="#organizations-api-keys-list" id="organizations-api-keys-list"></a>

GET `/api/v1/organizations/{organizationPk}/api-keys/`

{% hint style="info" %}
管理者による API Key の管理には「API Key 管理権限」が必要です。メンバーは複数の有効なキーを同時に保有できるため、新しいキーを発行してデプロイした後に、古いキーを失効できます。キーの取得方法は [API 認証方法](https://docs.maiagent.ai/api/preparation/authentication)を参照してください。
{% endhint %}

#### パラメータ

| パラメータ名           | 必須 | 型       | 説明                                             |
| ---------------- | -- | ------- | ---------------------------------------------- |
| `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.          |
| `query`          | ❌  | string  |                                                |
| `source`         | ❌  | string  |                                                |
| `status`         | ❌  | string  |                                                |

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/?page=1&pageSize=1&query=example&source=example&status=example" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/?page=1&pageSize=1&query=example&source=example&status=example", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/?page=1&pageSize=1&query=example&source=example&status=example", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマ例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string
      "name"?: string // A free-form name for the API key. Need not be unique. 50 characters max. (任意)
      "prefix": string
      "status": string
      "source": string
      "isActive"?: boolean // Reversible enable switch. A disabled key is rejected exactly like an unknown key (generic 401, no information leak), but keeps its secret and usage history and can be re-enabled at any time — unlike the irreversible revoked flag. (任意)
      "rateLimitRpm"?: integer // Max requests per minute across every platform API this key can call. Null = unlimited. (任意)
      "rateLimitTpm"?: integer // Max LLM tokens per minute through the AI Gateway inference endpoints. Null = unlimited. (任意)
      "creditBudgetDaily"?: string (decimal) // Max credits this key may spend through the AI Gateway per natural day (Asia/Taipei). Once reached, further inference calls are refused with 402 key_budget_exceeded until the next day. Null = unlimited. (任意)
      "creditBudgetMonthly"?: string (decimal) // Max credits this key may spend through the AI Gateway per calendar month (Asia/Taipei). Once reached, further inference calls are refused with 402 key_budget_exceeded until the next month. Null = unlimited. (任意)
      "creditUsedToday": string (decimal)
      "creditUsedThisMonth": string (decimal)
      "gatewayAllowedLlmCount": integer // Size of the gateway allow-list, when the queryset annotated it.

0 means "no restriction" (see ``api_key_allowed_llm_ids``). ``None``
on surfaces that did not annotate (login payload, PAT list) so a
missing count is never mistaken for "unrestricted".
      "expiryDate"?: string (timestamp) // Once API key expires, clients cannot use it anymore. (任意)
      "createdAt": string (timestamp)
      "lastUsedAt"?: string (timestamp) // 任意
      "member": object
      "createdByName": string
      "revokedAt"?: string (timestamp) // 任意
      "revokedByName": string
    }
  ]
}
```

**レスポンスのサンプル値**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "レスポンス文字列",
      "name": "レスポンス文字列",
      "prefix": "レスポンス文字列",
      "status": "レスポンス文字列",
      "source": "レスポンス文字列",
      "isActive": false,
      "rateLimitRpm": 456,
      "rateLimitTpm": 456,
      "creditBudgetDaily": "レスポンス文字列",
      "creditBudgetMonthly": "レスポンス文字列",
      "creditUsedToday": "レスポンス文字列",
      "creditUsedThisMonth": "レスポンス文字列",
      "gatewayAllowedLlmCount": 456,
      "expiryDate": "レスポンス文字列",
      "createdAt": "レスポンス文字列",
      "lastUsedAt": "レスポンス文字列",
      "member": {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "name": "レスポンスのサンプル名",
        "description": "レスポンスのサンプル説明"
      },
      "createdByName": "レスポンス文字列",
      "revokedAt": "レスポンス文字列",
      "revokedByName": "レスポンス文字列"
    }
  ]
}
```

**ステータスコード: 403 - 権限がありません**

***

### メンバーの API Key を発行 <a href="#organizations-api-keys-create" id="organizations-api-keys-create"></a>

POST `/api/v1/organizations/{organizationPk}/api-keys/`

#### パラメータ

| パラメータ名           | 必須 | 型      | 説明                                             |
| ---------------- | -- | ------ | ---------------------------------------------- |
| `organizationPk` | ✅  | string | A UUID string identifying this organization ID |

#### リクエストボディ

**リクエストパラメータ**

| フィールド               | 型                  | 必須  | 説明 |
| ------------------- | ------------------ | --- | -- |
| name                | string             | はい  |    |
| expiryDate          | string (timestamp) | いいえ |    |
| memberId            | string (uuid)      | はい  |    |
| isActive            | boolean            | いいえ |    |
| creditBudgetDaily   | string (decimal)   | いいえ |    |
| creditBudgetMonthly | string (decimal)   | いいえ |    |

**リクエストスキーマ例**

```typescript
{
  "name": string
  "expiryDate"?: string (timestamp) // 任意
  "memberId": string (uuid)
  "isActive"?: boolean // 任意
  "creditBudgetDaily"?: string (decimal) // 任意
  "creditBudgetMonthly"?: string (decimal) // 任意
}
```

**リクエストのサンプル値**

```json
{
  "name": "My API Key",
  "member_id": "00000000-0000-0000-0000-000000000000",
  "expiry_date": "2027-12-31T23:59:59Z"
}
```

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My API Key",
    "member_id": "00000000-0000-0000-0000-000000000000",
    "expiry_date": "2027-12-31T23:59:59Z"
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "name": "My API Key",
    "member_id": "00000000-0000-0000-0000-000000000000",
    "expiry_date": "2027-12-31T23:59:59Z"
  };

axios.post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "name": "My API Key",
    "member_id": "00000000-0000-0000-0000-000000000000",
    "expiry_date": "2027-12-31T23:59:59Z"
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => 'My API Key',
            'member_id' => '00000000-0000-0000-0000-000000000000',
            'expiry_date' => '2027-12-31T23:59:59Z'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 201**

**レスポンススキーマ例**

```typescript
{
  "id": string
  "name"?: string // A free-form name for the API key. Need not be unique. 50 characters max. (任意)
  "prefix": string
  "key": string // The full API key. Shown only in this response and never stored, so it
cannot be retrieved again.
  "status": string
  "source": string
  "isActive"?: boolean // Reversible enable switch. A disabled key is rejected exactly like an unknown key (generic 401, no information leak), but keeps its secret and usage history and can be re-enabled at any time — unlike the irreversible revoked flag. (任意)
  "expiryDate"?: string (timestamp) // Once API key expires, clients cannot use it anymore. (任意)
  "createdAt": string (timestamp)
}
```

**レスポンスのサンプル値**

```json
{
  "id": "レスポンス文字列",
  "name": "レスポンス文字列",
  "prefix": "レスポンス文字列",
  "key": "レスポンス文字列",
  "status": "レスポンス文字列",
  "source": "レスポンス文字列",
  "isActive": false,
  "expiryDate": "レスポンス文字列",
  "createdAt": "レスポンス文字列"
}
```

**ステータスコード: 400 - バリデーションエラー（例：名前が空、有効期限切れ）**

**ステータスコード: 403 - 権限がありません**

***

### 特定の API Key を取得 <a href="#organizations-api-keys-retrieve" id="organizations-api-keys-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/api-keys/{id}/`

#### パラメータ

| パラメータ名           | 必須 | 型      | 説明                                             |
| ---------------- | -- | ------ | ---------------------------------------------- |
| `id`             | ✅  | string |                                                |
| `organizationPk` | ✅  | string | A UUID string identifying this organization ID |

#### コード例

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

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

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマ例**

```typescript
{
  "id": string
  "name"?: string // A free-form name for the API key. Need not be unique. 50 characters max. (任意)
  "prefix": string
  "status": string
  "source": string
  "isActive"?: boolean // Reversible enable switch. A disabled key is rejected exactly like an unknown key (generic 401, no information leak), but keeps its secret and usage history and can be re-enabled at any time — unlike the irreversible revoked flag. (任意)
  "rateLimitRpm"?: integer // Max requests per minute across every platform API this key can call. Null = unlimited. (任意)
  "rateLimitTpm"?: integer // Max LLM tokens per minute through the AI Gateway inference endpoints. Null = unlimited. (任意)
  "creditBudgetDaily"?: string (decimal) // Max credits this key may spend through the AI Gateway per natural day (Asia/Taipei). Once reached, further inference calls are refused with 402 key_budget_exceeded until the next day. Null = unlimited. (任意)
  "creditBudgetMonthly"?: string (decimal) // Max credits this key may spend through the AI Gateway per calendar month (Asia/Taipei). Once reached, further inference calls are refused with 402 key_budget_exceeded until the next month. Null = unlimited. (任意)
  "creditUsedToday": string (decimal)
  "creditUsedThisMonth": string (decimal)
  "gatewayAllowedLlmCount": integer // Size of the gateway allow-list, when the queryset annotated it.

0 means "no restriction" (see ``api_key_allowed_llm_ids``). ``None``
on surfaces that did not annotate (login payload, PAT list) so a
missing count is never mistaken for "unrestricted".
  "expiryDate"?: string (timestamp) // Once API key expires, clients cannot use it anymore. (任意)
  "createdAt": string (timestamp)
  "lastUsedAt"?: string (timestamp) // 任意
  "member": object
  "createdByName": string
  "revokedAt"?: string (timestamp) // 任意
  "revokedByName": string
  "gatewayAllowedLlmIds": [
    string (uuid)
  ]
}
```

**レスポンスのサンプル値**

```json
{
  "id": "レスポンス文字列",
  "name": "レスポンス文字列",
  "prefix": "レスポンス文字列",
  "status": "レスポンス文字列",
  "source": "レスポンス文字列",
  "isActive": false,
  "rateLimitRpm": 456,
  "rateLimitTpm": 456,
  "creditBudgetDaily": "レスポンス文字列",
  "creditBudgetMonthly": "レスポンス文字列",
  "creditUsedToday": "レスポンス文字列",
  "creditUsedThisMonth": "レスポンス文字列",
  "gatewayAllowedLlmCount": 456,
  "expiryDate": "レスポンス文字列",
  "createdAt": "レスポンス文字列",
  "lastUsedAt": "レスポンス文字列",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンスのサンプル名",
    "description": "レスポンスのサンプル説明"
  },
  "createdByName": "レスポンス文字列",
  "revokedAt": "レスポンス文字列",
  "revokedByName": "レスポンス文字列",
  "gatewayAllowedLlmIds": [
    "550e8400-e29b-41d4-a716-446655440000"
  ]
}
```

***

### API Key の設定を更新 <a href="#organizations-api-keys-partial-update" id="organizations-api-keys-partial-update"></a>

PATCH `/api/v1/organizations/{organizationPk}/api-keys/{id}/`

{% hint style="info" %}
有効・無効の状態、1 分あたりのリクエスト数（RPM）、有効期限を変更できます。無効にしたキーは再び有効にできます。キーを失効させるには `DELETE` を使用します。
{% endhint %}

#### パラメータ

| パラメータ名           | 必須 | 型      | 説明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `id`             | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### リクエストボディ

**リクエストパラメータ**

| フィールド               | 型                  | 必須  | 説明                                                                                                                                                                                                            |
| ------------------- | ------------------ | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name                | string             | いいえ | A free-form name for the API key. Need not be unique. 50 characters max.                                                                                                                                      |
| isActive            | boolean            | いいえ | Reversible enable switch. A disabled key is rejected exactly like an unknown key (generic 401, no information leak), but keeps its secret and usage history and can be re-enabled at any time — unlike t...   |
| rateLimitRpm        | integer            | いいえ | Max requests per minute across every platform API this key can call. Null = unlimited.                                                                                                                        |
| rateLimitTpm        | integer            | いいえ | Max LLM tokens per minute through the AI Gateway inference endpoints. Null = unlimited.                                                                                                                       |
| creditBudgetDaily   | string (decimal)   | いいえ | Max credits this key may spend through the AI Gateway per natural day (Asia/Taipei). Once reached, further inference calls are refused with 402 key\_budget\_exceeded until the next day. Null = unlimited... |
| creditBudgetMonthly | string (decimal)   | いいえ | Max credits this key may spend through the AI Gateway per calendar month (Asia/Taipei). Once reached, further inference calls are refused with 402 key\_budget\_exceeded until the next month. Null = unli... |
| expiryDate          | string (timestamp) | いいえ | Once API key expires, clients cannot use it anymore.                                                                                                                                                          |
| lastUsedAt          | string (timestamp) | いいえ |                                                                                                                                                                                                               |
| revokedAt           | string (timestamp) | いいえ |                                                                                                                                                                                                               |

**リクエストスキーマの例**

```typescript
{
  "name"?: string // A free-form name for the API key. Need not be unique. 50 characters max. (任意)
  "isActive"?: boolean // Reversible enable switch. A disabled key is rejected exactly like an unknown key (generic 401, no information leak), but keeps its secret and usage history and can be re-enabled at any time — unlike the irreversible revoked flag. (任意)
  "rateLimitRpm"?: integer // Max requests per minute across every platform API this key can call. Null = unlimited. (任意)
  "rateLimitTpm"?: integer // Max LLM tokens per minute through the AI Gateway inference endpoints. Null = unlimited. (任意)
  "creditBudgetDaily"?: string (decimal) // Max credits this key may spend through the AI Gateway per natural day (Asia/Taipei). Once reached, further inference calls are refused with 402 key_budget_exceeded until the next day. Null = unlimited. (任意)
  "creditBudgetMonthly"?: string (decimal) // Max credits this key may spend through the AI Gateway per calendar month (Asia/Taipei). Once reached, further inference calls are refused with 402 key_budget_exceeded until the next month. Null = unlimited. (任意)
  "expiryDate"?: string (timestamp) // Once API key expires, clients cannot use it anymore. (任意)
  "lastUsedAt"?: string (timestamp) // 任意
  "revokedAt"?: string (timestamp) // 任意
}
```

**リクエストのサンプル値**

```json
{
  "name": "サンプル名",
  "isActive": true,
  "rateLimitRpm": 123,
  "rateLimitTpm": 123,
  "creditBudgetDaily": "サンプル文字列",
  "creditBudgetMonthly": "サンプル文字列",
  "expiryDate": "サンプル文字列",
  "lastUsedAt": "サンプル文字列",
  "revokedAt": "サンプル文字列"
}
```

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "サンプル名",
    "isActive": true,
    "rateLimitRpm": 123,
    "rateLimitTpm": 123,
    "creditBudgetDaily": "サンプル文字列",
    "creditBudgetMonthly": "サンプル文字列",
    "expiryDate": "サンプル文字列",
    "lastUsedAt": "サンプル文字列",
    "revokedAt": "サンプル文字列"
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "name": "サンプル名",
    "isActive": true,
    "rateLimitRpm": 123,
    "rateLimitTpm": 123,
    "creditBudgetDaily": "サンプル文字列",
    "creditBudgetMonthly": "サンプル文字列",
    "expiryDate": "サンプル文字列",
    "lastUsedAt": "サンプル文字列",
    "revokedAt": "サンプル文字列"
  };

axios.patch("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "name": "サンプル名",
    "isActive": True,
    "rateLimitRpm": 123,
    "rateLimitTpm": 123,
    "creditBudgetDaily": "サンプル文字列",
    "creditBudgetMonthly": "サンプル文字列",
    "expiryDate": "サンプル文字列",
    "lastUsedAt": "サンプル文字列",
    "revokedAt": "サンプル文字列"
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("レスポンスを取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => 'サンプル名',
            'isActive' => true,
            'rateLimitRpm' => 123,
            'rateLimitTpm' => 123,
            'creditBudgetDaily' => 'サンプル文字列',
            'creditBudgetMonthly' => 'サンプル文字列',
            'expiryDate' => 'サンプル文字列',
            'lastUsedAt' => 'サンプル文字列',
            'revokedAt' => 'サンプル文字列'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string
  "name"?: string // A free-form name for the API key. Need not be unique. 50 characters max. (任意)
  "prefix": string
  "status": string
  "source": string
  "isActive"?: boolean // Reversible enable switch. A disabled key is rejected exactly like an unknown key (generic 401, no information leak), but keeps its secret and usage history and can be re-enabled at any time — unlike the irreversible revoked flag. (任意)
  "rateLimitRpm"?: integer // Max requests per minute across every platform API this key can call. Null = unlimited. (任意)
  "rateLimitTpm"?: integer // Max LLM tokens per minute through the AI Gateway inference endpoints. Null = unlimited. (任意)
  "creditBudgetDaily"?: string (decimal) // Max credits this key may spend through the AI Gateway per natural day (Asia/Taipei). Once reached, further inference calls are refused with 402 key_budget_exceeded until the next day. Null = unlimited. (任意)
  "creditBudgetMonthly"?: string (decimal) // Max credits this key may spend through the AI Gateway per calendar month (Asia/Taipei). Once reached, further inference calls are refused with 402 key_budget_exceeded until the next month. Null = unlimited. (任意)
  "creditUsedToday": string (decimal)
  "creditUsedThisMonth": string (decimal)
  "gatewayAllowedLlmCount": integer // Size of the gateway allow-list, when the queryset annotated it.

0 means "no restriction" (see ``api_key_allowed_llm_ids``). ``None``
on surfaces that did not annotate (login payload, PAT list) so a
missing count is never mistaken for "unrestricted".
  "expiryDate"?: string (timestamp) // Once API key expires, clients cannot use it anymore. (任意)
  "createdAt": string (timestamp)
  "lastUsedAt"?: string (timestamp) // 任意
  "member": object
  "createdByName": string
  "revokedAt"?: string (timestamp) // 任意
  "revokedByName": string
  "gatewayAllowedLlmIds": [
    string (uuid)
  ]
}
```

**レスポンスのサンプル値**

```json
{
  "id": "レスポンス文字列",
  "name": "レスポンス文字列",
  "prefix": "レスポンス文字列",
  "status": "レスポンス文字列",
  "source": "レスポンス文字列",
  "isActive": false,
  "rateLimitRpm": 456,
  "rateLimitTpm": 456,
  "creditBudgetDaily": "レスポンス文字列",
  "creditBudgetMonthly": "レスポンス文字列",
  "creditUsedToday": "レスポンス文字列",
  "creditUsedThisMonth": "レスポンス文字列",
  "gatewayAllowedLlmCount": 456,
  "expiryDate": "レスポンス文字列",
  "createdAt": "レスポンス文字列",
  "lastUsedAt": "レスポンス文字列",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "レスポンスのサンプル名",
    "description": "レスポンスのサンプル説明"
  },
  "createdByName": "レスポンス文字列",
  "revokedAt": "レスポンス文字列",
  "revokedByName": "レスポンス文字列",
  "gatewayAllowedLlmIds": [
    "550e8400-e29b-41d4-a716-446655440000"
  ]
}
```

***

### API Key を失効 <a href="#organizations-api-keys-destroy" id="organizations-api-keys-destroy"></a>

DELETE `/api/v1/organizations/{organizationPk}/api-keys/{id}/`

#### パラメータ

| パラメータ名           | 必須 | 型      | 説明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `id`             | ✅  | string |                                      |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエストボディ (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラー:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.delete(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラー:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/api-keys/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラー: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

| ステータスコード | 説明                  |
| -------- | ------------------- |
| 204      | API Key を失効しました     |
| 400      | API Key はすでに失効しています |
| 403      | 権限が不足しています          |
| 404      | API Key が見つかりません    |

***

### API Key が属する組織を取得 <a href="#users-api-key-context-retrieve" id="users-api-key-context-retrieve"></a>

GET `/api/v1/users/api-key-context/`

{% hint style="info" %}
`Authorization: Api-Key` のみを受け付け、キーに紐づく組織を返します。キーの RPM 上限にはカウントされません。用途は [共通規約：キーが属する組織の確認](https://docs.maiagent.ai/api/preparation/conventions#api-key-context)。
{% endhint %}

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/users/api-key-context/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/users/api-key-context/", config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラー:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/users/api-key-context/"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラー:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/users/api-key-context/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラー: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "organizationId": string (uuid)
}
```

**レスポンス値の例**

```json
{
  "organizationId": "550e8400-e29b-41d4-a716-446655440000"
}
```

**ステータスコード: 401 - API Key がない、または無効です。もしくは API Key 以外の認証情報が使用されました**

***

### メンバー埋め込みトークンを発行 <a href="#members-embed-tokens-create" id="members-embed-tokens-create"></a>

POST `/api/v1/members/embed-tokens/`

{% hint style="info" %}
組織の API Key を使用して、指定したメンバー用に有効期間 15 分のトークンを発行します。お客様のシステムがそのメンバーとして MaiGPT を埋め込むために使用します。呼び出せるのは、組織オーナー、または「組織概要」の管理権限を持つメンバーが保有するキーのみです。フローは技術マニュアル [MaiGPT メンバー ID 埋め込み](https://docs.maiagent.ai/tech/work/maigpt-integration)。
{% endhint %}

#### リクエストボディ

**リクエストパラメータ**

| フィールド    | 型              | 必須  | 説明 |
| -------- | -------------- | --- | -- |
| email    | string (email) | いいえ |    |
| memberId | string (uuid)  | いいえ |    |

**リクエストスキーマの例**

```typescript
{
  "email"?: string (email) // 任意
  "memberId"?: string (uuid) // 任意
}
```

**リクエスト値の例**

```json
{
  "email": "user@example.com",
  "memberId": "550e8400-e29b-41d4-a716-446655440000"
}
```

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/members/embed-tokens/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "memberId": "550e8400-e29b-41d4-a716-446655440000"
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "email": "user@example.com",
    "memberId": "550e8400-e29b-41d4-a716-446655440000"
  };

axios.post("https://api.maiagent.ai/api/v1/members/embed-tokens/", data, config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "email": "user@example.com",
    "memberId": "550e8400-e29b-41d4-a716-446655440000"
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/members/embed-tokens/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'email' => 'user@example.com',
            'memberId' => '550e8400-e29b-41d4-a716-446655440000'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 201**

**レスポンススキーマの例**

```typescript
{
  "accessToken": string
  "organizationId": string (uuid)
  "expiresAt": string (timestamp)
  "member": {
  {
    "id": string (uuid)
    "userId": string (uuid)
    "email": string (email)
    "name": string
  }
  }
}
```

**レスポンス値の例**

```json
{
  "accessToken": "レスポンス文字列",
  "organizationId": "550e8400-e29b-41d4-a716-446655440000",
  "expiresAt": "レスポンス文字列",
  "member": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "userId": "550e8400-e29b-41d4-a716-446655440000",
    "email": "response@example.com",
    "name": "レスポンス文字列"
  }
}
```

**ステータスコード: 400 - email と memberId のうち、いずれか一方のみを指定する必要があります**

**ステータスコード: 401 - Api-Key で認証されていません**

**ステータスコード: 403 - API Key の保有者が組織オーナーではなく、組織管理権限も持っていません**

**ステータスコード: 404 - 指定されたメンバーが存在しない、無効化されている、またはこの組織に属していません**

***

### OAuth アプリケーション一覧の取得 <a href="#oauth-applications-list" id="oauth-applications-list"></a>

GET `/api/v1/oauth/applications/`

{% hint style="info" %}
MaiAgent を OAuth 2.1 認可サーバーとして利用する場合、アプリケーションをまずここで登録します。手順は技術マニュアルの [MaiAgent を OAuth 認可サーバーとして利用する](https://docs.maiagent.ai/tech/authorization-integration/maiagent-oauth-server) を参照してください。
{% endhint %}

#### パラメータ

| パラメータ名     | 必須 | 型       | 説明                                             |
| ---------- | -- | ------- | ---------------------------------------------- |
| `page`     | ❌  | integer | A page number within the paginated result set. |
| `pageSize` | ❌  | integer | Number of results to return per page.          |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/oauth/applications/?page=1&pageSize=1" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/oauth/applications/?page=1&pageSize=1", config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/oauth/applications/?page=1&pageSize=1"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/oauth/applications/?page=1&pageSize=1", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string (uuid)
      "name": string
      "clientId": string
      "clientType": 
      {
      }
      "redirectUris": [
        string
      ]
      "authorizedUserCount": integer
      "createdByName": string
      "created": string (timestamp)
      "updated": string (timestamp)
    }
  ]
}
```

**レスポンス値の例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス文字列",
      "clientId": "レスポンス文字列",
      "clientType": {},
      "redirectUris": [
        "レスポンス文字列"
      ],
      "authorizedUserCount": 456,
      "createdByName": "レスポンス文字列",
      "created": "レスポンス文字列",
      "updated": "レスポンス文字列"
    }
  ]
}
```

***

### OAuth アプリケーションの登録 <a href="#oauth-applications-create" id="oauth-applications-create"></a>

POST `/api/v1/oauth/applications/`

#### リクエストボディ

**リクエストパラメータ**

| フィールド        | 型              | 必須  | 説明 |
| ------------ | -------------- | --- | -- |
| name         | string         | はい  |    |
| clientType   | object         | いいえ |    |
| redirectUris | array\[string] | はい  |    |

**リクエストスキーマの例**

```typescript
{
  "name": string
  "clientType"?:  // 任意
  {
  }
  "redirectUris": [
    string
  ]
}
```

**リクエスト値の例**

```json
{
  "name": "サンプル名",
  "clientType": {},
  "redirectUris": [
    "サンプル文字列"
  ]
}
```

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/oauth/applications/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "サンプル名",
    "clientType": {},
    "redirectUris": [
      "サンプル文字列"
    ]
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "name": "サンプル名",
    "clientType": {},
    "redirectUris": [
      "サンプル文字列"
    ]
  };

axios.post("https://api.maiagent.ai/api/v1/oauth/applications/", data, config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "name": "サンプル名",
    "clientType": {},
    "redirectUris": [
        "サンプル文字列"
    ]
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/oauth/applications/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => 'サンプル名',
            'clientType' => new \stdClass(),
            'redirectUris' => [
                'サンプル文字列'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 201**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "name": string
  "clientId": string
  "clientType": 
  {
  }
  "redirectUris": [
    string
  ]
  "authorizedUserCount": integer
  "createdByName": string
  "created": string (timestamp)
  "updated": string (timestamp)
  "clientSecret": string
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "clientId": "レスポンス文字列",
  "clientType": {},
  "redirectUris": [
    "レスポンス文字列"
  ],
  "authorizedUserCount": 456,
  "createdByName": "レスポンス文字列",
  "created": "レスポンス文字列",
  "updated": "レスポンス文字列",
  "clientSecret": "レスポンス文字列"
}
```

***

### 特定の OAuth アプリケーションの取得 <a href="#oauth-applications-retrieve" id="oauth-applications-retrieve"></a>

GET `/api/v1/oauth/applications/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                                                         |
| ------ | -- | ------ | ---------------------------------------------------------- |
| `id`   | ✅  | string | A UUID string identifying this MaiAgent OAuth application. |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/", config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "name": string
  "clientId": string
  "clientType": 
  {
  }
  "redirectUris": [
    string
  ]
  "authorizedUserCount": integer
  "createdByName": string
  "created": string (timestamp)
  "updated": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "clientId": "レスポンス文字列",
  "clientType": {},
  "redirectUris": [
    "レスポンス文字列"
  ],
  "authorizedUserCount": 456,
  "createdByName": "レスポンス文字列",
  "created": "レスポンス文字列",
  "updated": "レスポンス文字列"
}
```

***

### OAuth アプリケーションの更新 <a href="#oauth-applications-partial-update" id="oauth-applications-partial-update"></a>

PATCH `/api/v1/oauth/applications/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                                                         |
| ------ | -- | ------ | ---------------------------------------------------------- |
| `id`   | ✅  | string | A UUID string identifying this MaiAgent OAuth application. |

#### リクエストボディ

**リクエストパラメータ**

| フィールド        | 型              | 必須  | 説明 |
| ------------ | -------------- | --- | -- |
| name         | string         | いいえ |    |
| redirectUris | array\[string] | いいえ |    |

**リクエストスキーマの例**

```typescript
{
  "name"?: string // 任意
  "redirectUris"?: [ // 任意
    string
  ]
}
```

**リクエスト値の例**

```json
{
  "name": "サンプル名",
  "redirectUris": [
    "サンプル文字列"
  ]
}
```

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "サンプル名",
    "redirectUris": [
      "サンプル文字列"
    ]
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "name": "サンプル名",
    "redirectUris": [
      "サンプル文字列"
    ]
  };

axios.patch("https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "name": "サンプル名",
    "redirectUris": [
        "サンプル文字列"
    ]
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'name' => 'サンプル名',
            'redirectUris' => [
                'サンプル文字列'
            ]
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "name": string
  "clientId": string
  "clientType": 
  {
  }
  "redirectUris": [
    string
  ]
  "authorizedUserCount": integer
  "createdByName": string
  "created": string (timestamp)
  "updated": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "clientId": "レスポンス文字列",
  "clientType": {},
  "redirectUris": [
    "レスポンス文字列"
  ],
  "authorizedUserCount": 456,
  "createdByName": "レスポンス文字列",
  "created": "レスポンス文字列",
  "updated": "レスポンス文字列"
}
```

***

### OAuth アプリケーションの削除と token の取り消し <a href="#oauth-applications-destroy" id="oauth-applications-destroy"></a>

DELETE `/api/v1/oauth/applications/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                                                         |
| ------ | -- | ------ | ---------------------------------------------------------- |
| `id`   | ✅  | string | A UUID string identifying this MaiAgent OAuth application. |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエストボディ (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.delete(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

| ステータスコード | 説明               |
| -------- | ---------------- |
| 204      | No response body |

***

### client secret の再生成 <a href="#oauth-applications-regenerate-secret-create" id="oauth-applications-regenerate-secret-create"></a>

POST `/api/v1/oauth/applications/{id}/regenerate-secret/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                                                         |
| ------ | -- | ------ | ---------------------------------------------------------- |
| `id`   | ✅  | string | A UUID string identifying this MaiAgent OAuth application. |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/regenerate-secret/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエストボディ (payload)
const data = null;

axios.post("https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/regenerate-secret/", data, config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラー:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.post(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラー:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/oauth/applications/550e8400-e29b-41d4-a716-446655440000/regenerate-secret/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラー: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "name": string
  "clientId": string
  "clientType": 
  {
  }
  "redirectUris": [
    string
  ]
  "authorizedUserCount": integer
  "createdByName": string
  "created": string (timestamp)
  "updated": string (timestamp)
  "clientSecret": string
}
```

**レスポンス例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "レスポンス文字列",
  "clientId": "レスポンス文字列",
  "clientType": {},
  "redirectUris": [
    "レスポンス文字列"
  ],
  "authorizedUserCount": 456,
  "createdByName": "レスポンス文字列",
  "created": "レスポンス文字列",
  "updated": "レスポンス文字列",
  "clientSecret": "レスポンス文字列"
}
```

***

### 自分が認可した OAuth アプリケーションを一覧表示 <a href="#oauth-authorized-applications-list" id="oauth-authorized-applications-list"></a>

GET `/api/v1/oauth/authorized-applications/`

#### パラメータ

| パラメータ名     | 必須 | 型       | 説明                                             |
| ---------- | -- | ------- | ---------------------------------------------- |
| `page`     | ❌  | integer | A page number within the paginated result set. |
| `pageSize` | ❌  | integer | Number of results to return per page.          |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/oauth/authorized-applications/?page=1&pageSize=1" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/oauth/authorized-applications/?page=1&pageSize=1", config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラー:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/oauth/authorized-applications/?page=1&pageSize=1"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラー:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/oauth/authorized-applications/?page=1&pageSize=1", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラー: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "id": string (uuid)
      "name": string
      "organization": string (uuid)
      "organizationName": string
      "tokenCount": integer
      "lastAuthorizedAt": string (timestamp)
      "latestExpiresAt": string (timestamp)
    }
  ]
}
```

**レスポンス例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "レスポンス文字列",
      "organization": "550e8400-e29b-41d4-a716-446655440000",
      "organizationName": "レスポンス文字列",
      "tokenCount": 456,
      "lastAuthorizedAt": "レスポンス文字列",
      "latestExpiresAt": "レスポンス文字列"
    }
  ]
}
```

***

### アプリケーションに対する自分の認可を取り消す <a href="#oauth-authorized-applications-destroy" id="oauth-authorized-applications-destroy"></a>

DELETE `/api/v1/oauth/authorized-applications/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明 |
| ------ | -- | ------ | -- |
| `id`   | ✅  | string |    |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/oauth/authorized-applications/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエストボディ (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/oauth/authorized-applications/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラー:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.delete(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラー:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/oauth/authorized-applications/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラー: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

| ステータスコード | 説明               |
| -------- | ---------------- |
| 204      | No response body |

***

### 組織を削除 <a href="#organizations-destroy" id="organizations-destroy"></a>

DELETE `/api/v1/organizations/{id}/`

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                                 |
| ------ | -- | ------ | ---------------------------------- |
| `id`   | ✅  | string | A UUID string identifying this 組織. |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエストボディ (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラー:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.delete(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラー:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラー: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

| ステータスコード | 説明               |
| -------- | ---------------- |
| 204      | No response body |

***

### 指定したメンバーを削除 <a href="#organizations-members-destroy" id="organizations-members-destroy"></a>

DELETE `/api/v1/organizations/{organizationPk}/members/{id}/`

#### パラメータ

| パラメータ名           | 必須 | 型      | 説明                                   |
| ---------------- | -- | ------ | ------------------------------------ |
| `id`             | ✅  | string | A UUID string identifying this メンバー. |
| `organizationPk` | ✅  | string | A UUID string identifying this 組織 ID |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエストボディ (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラー:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.delete(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラー:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/members/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラー: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

| ステータスコード | 説明               |
| -------- | ---------------- |
| 204      | No response body |

***

### メンバー使用統計を取得 <a href="#organizations-usage-statistics-members-list" id="organizations-usage-statistics-members-list"></a>

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

#### パラメータ

| パラメータ名            | 必須 | 型       | 説明                                                                                                              |
| ----------------- | -- | ------- | --------------------------------------------------------------------------------------------------------------- |
| `organizationPk`  | ✅  | string  | A UUID string identifying this 組織 ID                                                                            |
| `chatbot`         | ❌  | string  | 特定の AI アシスタント ID で絞り込み                                                                                          |
| `chatbotId`       | ❌  | string  |                                                                                                                 |
| `endDate`         | ❌  | string  | 終了日、形式: YYYY-MM-DD                                                                                              |
| `includeTime`     | ❌  | boolean | 時間のみで集計した時系列データを返すかどうか。トレンドグラフ用です（true/false）。true に設定すると、レスポンスにはエンティティ情報が含まれず、時間フィールドと統計値のみが返され、ページネーションされません。 |
| `memberId`        | ❌  | string  |                                                                                                                 |
| `page`            | ❌  | integer | ページ番号                                                                                                           |
| `pageSize`        | ❌  | integer | 1 ページあたりの件数                                                                                                     |
| `search`          | ❌  | string  | メンバー ID、名前、または Email で検索                                                                                        |
| `sortBy`          | ❌  | string  | 並べ替えフィールド                                                                                                       |
| `sortOrder`       | ❌  | string  | 並べ替え順序 (asc/desc)                                                                                               |
| `startDate`       | ✅  | string  | 開始日、形式: YYYY-MM-DD                                                                                              |
| `timeGranularity` | ❌  | string  | 時間の粒度 (hour/day/month)                                                                                          |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/members/?chatbot=example&chatbotId=550e8400-e29b-41d4-a716-446655440000&endDate=example&includeTime=true&memberId=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&search=example&sortBy=conversations_count&sortOrder=asc&startDate=example&timeGranularity=day" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/members/?chatbot=example&chatbotId=550e8400-e29b-41d4-a716-446655440000&endDate=example&includeTime=true&memberId=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&search=example&sortBy=conversations_count&sortOrder=asc&startDate=example&timeGranularity=day", config)
  .then(response => {
    console.log('レスポンスを正常に受信しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストエラー:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/members/?chatbot=example&chatbotId=550e8400-e29b-41d4-a716-446655440000&endDate=example&includeTime=true&memberId=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&search=example&sortBy=conversations_count&sortOrder=asc&startDate=example&timeGranularity=day"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に受信しました:")
    print(response.json())
except Exception as e:
    print("リクエストエラー:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/members/?chatbot=example&chatbotId=550e8400-e29b-41d4-a716-446655440000&endDate=example&includeTime=true&memberId=550e8400-e29b-41d4-a716-446655440000&page=1&pageSize=1&search=example&sortBy=conversations_count&sortOrder=asc&startDate=example&timeGranularity=day", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に受信しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストエラー: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "count"?: integer // 結果の件数 (任意)
      "results"?: [ // 任意
        {
          "member"?: { // 任意
          {
            "id"?: string (uuid) // メンバー ID (任意)
            "name"?: string // メンバー名 (任意)
            "email"?: string // メンバーのメールアドレス (任意)
          }
          }
          "datetime"?: string (date-time) // タイムスタンプ（include_time=true かつ time_granularity=hour の場合のみ出力） (任意)
          "period"?: string (date) // 日付（include_time=true かつ time_granularity=day/month の場合のみ出力） (任意)
          "input_characters_count"?: integer // 入力文字数 (任意)
          "output_characters_count"?: integer // 出力文字数 (任意)
          "input_token_usage"?: integer // 入力トークン数 (任意)
          "output_token_usage"?: integer // 出力トークン数 (任意)
          "messages_count"?: integer // メッセージ数 (任意)
          "conversations_count"?: integer // 会話数 (任意)
          "total_characters_count"?: integer // 総文字数 (任意)
          "total_token_usage"?: integer // 総トークン数 (任意)
        }
      ]
    }
  ]
}
```

**レスポンス例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "count": 2,
      "results": [
        {
          "member": {
            "id": "3a245511-d5e0-4e06-9dc6-1106915b9a8a",
            "name": "山田太郎",
            "email": "wang@example.com"
          },
          "input_characters_count": 10000,
          "output_characters_count": 15000,
          "input_token_usage": 2500,
          "output_token_usage": 3750,
          "messages_count": 100,
          "conversations_count": 50,
          "total_characters_count": 25000,
          "total_token_usage": 6250
        }
      ]
    }
  ]
}
```

***

### メンバーの使用統計サマリーを取得 <a href="#organizations-usage-statistics-members-summary-retrieve" id="organizations-usage-statistics-members-summary-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/usage-statistics/members/summary/`

#### パラメータ

| パラメータ名            | 必須 | 型      | 説明                       |
| ----------------- | -- | ------ | ------------------------ |
| `organizationPk`  | ✅  | string | 組織 ID を識別する UUID 文字列です   |
| `endDate`         | ❌  | string | 終了日です。形式: YYYY-MM-DD     |
| `startDate`       | ✅  | string | 開始日です。形式: YYYY-MM-DD     |
| `timeGranularity` | ❌  | string | 時間の粒度です (hour/day/month) |

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/members/summary/?endDate=example&startDate=example&timeGranularity=day" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/members/summary/?endDate=example&startDate=example&timeGranularity=day", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/members/summary/?endDate=example&startDate=example&timeGranularity=day"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/members/summary/?endDate=example&startDate=example&timeGranularity=day", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "totalInputCharacters"?: integer // 入力文字数の合計 (任意)
  "totalOutputCharacters"?: integer // 出力文字数の合計 (任意)
  "totalCharacters"?: integer // 文字数の合計 (任意)
  "totalInputTokens"?: integer // 入力トークン数の合計 (任意)
  "totalOutputTokens"?: integer // 出力トークン数の合計 (任意)
  "totalTokens"?: integer // トークン数の合計 (任意)
  "totalMessages"?: integer // メッセージ数の合計 (任意)
  "totalConversations"?: integer // 会話数の合計 (任意)
  "chatbotScope"?: string (enum: organization, accessible_chatbots) // 呼び出し元の使用量統計の範囲です。organization＝組織全体、accessible_chatbots＝呼び出し元が所属するロールに許可された AI アシスタントのみ (任意)
  "totalCount"?: integer // 検索条件に一致するメンバーの時間別統計レコード数です。同じメンバーでも時間帯や AI アシスタントが異なれば別のレコードとして数えます。メンバー数ではありません (任意)
}
```

**レスポンス値の例**

```json
{
  "totalInputCharacters": 456,
  "totalOutputCharacters": 456,
  "totalCharacters": 456,
  "totalInputTokens": 456,
  "totalOutputTokens": 456,
  "totalTokens": 456,
  "totalMessages": 456,
  "totalConversations": 456,
  "chatbotScope": "organization",
  "totalCount": 456
}
```

***

### AI アシスタント使用統計の取得 <a href="#organizations-usage-statistics-chatbots-list" id="organizations-usage-statistics-chatbots-list"></a>

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

#### パラメータ

| パラメータ名            | 必須 | 型       | 説明                                                                                                                |
| ----------------- | -- | ------- | ----------------------------------------------------------------------------------------------------------------- |
| `organizationPk`  | ✅  | string  | A UUID string identifying this 組織 ID                                                                              |
| `chatbotId`       | ❌  | string  |                                                                                                                   |
| `endDate`         | ❌  | string  | 終了日、形式: YYYY-MM-DD                                                                                                |
| `includeTime`     | ❌  | boolean | 時間のみで集計した時系列データを返すかどうか。トレンドグラフ用です（true/false）。true に設定すると、レスポンスにはエンティティ情報が含まれず、時間フィールドと統計値のみが返され、ページネーションは行われません。 |
| `page`            | ❌  | integer | ページ番号                                                                                                             |
| `pageSize`        | ❌  | integer | 1 ページあたりの件数                                                                                                       |
| `search`          | ❌  | string  | AI アシスタントの ID または名前で検索                                                                                            |
| `sortBy`          | ❌  | string  | 並べ替えフィールド                                                                                                         |
| `sortOrder`       | ❌  | string  | 並び順 (asc/desc)                                                                                                    |
| `startDate`       | ✅  | string  | 開始日、形式: YYYY-MM-DD                                                                                                |
| `timeGranularity` | ❌  | string  | 時間粒度 (hour/day/month)                                                                                             |

#### コード例

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

```bash
# API 呼び出しの例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/chatbots/?chatbotId=550e8400-e29b-41d4-a716-446655440000&endDate=example&includeTime=true&page=1&pageSize=1&search=example&sortBy=conversations_count&sortOrder=asc&startDate=example&timeGranularity=day" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/chatbots/?chatbotId=550e8400-e29b-41d4-a716-446655440000&endDate=example&includeTime=true&page=1&pageSize=1&search=example&sortBy=conversations_count&sortOrder=asc&startDate=example&timeGranularity=day", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/chatbots/?chatbotId=550e8400-e29b-41d4-a716-446655440000&endDate=example&includeTime=true&page=1&pageSize=1&search=example&sortBy=conversations_count&sortOrder=asc&startDate=example&timeGranularity=day"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/chatbots/?chatbotId=550e8400-e29b-41d4-a716-446655440000&endDate=example&includeTime=true&page=1&pageSize=1&search=example&sortBy=conversations_count&sortOrder=asc&startDate=example&timeGranularity=day", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 任意
  "previous"?: string (uri) // 任意
  "results": [
    {
      "count"?: integer // 結果件数 (任意)
      "results"?: [ // 任意
        {
          "chatbot"?: { // 任意
          {
            "id"?: string (uuid) // AI アシスタント ID (任意)
            "name"?: string // AI アシスタント名 (任意)
          }
          }
          "datetime"?: string (date-time) // タイムスタンプ（include_time=true かつ time_granularity=hour の場合のみ表示） (任意)
          "period"?: string (date) // 日付（include_time=true かつ time_granularity=day/month の場合のみ表示） (任意)
          "input_characters_count"?: integer // 入力文字数 (任意)
          "output_characters_count"?: integer // 出力文字数 (任意)
          "input_token_usage"?: integer // 入力トークン数 (任意)
          "output_token_usage"?: integer // 出力トークン数 (任意)
          "messages_count"?: integer // メッセージ数 (任意)
          "conversations_count"?: integer // 会話数 (任意)
          "total_characters_count"?: integer // 総文字数 (任意)
          "total_token_usage"?: integer // 総トークン数 (任意)
        }
      ]
    }
  ]
}
```

**レスポンスの値の例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "count": 2,
      "results": [
        {
          "chatbot": {
            "id": "5b646600-f6e0-4f07-aec7-0207a26c0a9b",
            "name": "カスタマーサポートアシスタント"
          },
          "input_characters_count": 10000,
          "output_characters_count": 15000,
          "input_token_usage": 2500,
          "output_token_usage": 3750,
          "messages_count": 100,
          "conversations_count": 50,
          "total_characters_count": 25000,
          "total_token_usage": 6250
        }
      ]
    }
  ]
}
```

***

### AI アシスタントの利用統計サマリーを取得 <a href="#organizations-usage-statistics-chatbots-summary-retrieve" id="organizations-usage-statistics-chatbots-summary-retrieve"></a>

GET `/api/v1/organizations/{organizationPk}/usage-statistics/chatbots/summary/`

#### パラメータ

| パラメータ名            | 必須 | 型      | 説明                       |
| ----------------- | -- | ------ | ------------------------ |
| `organizationPk`  | ✅  | string | この組織 ID を識別する UUID 文字列です |
| `endDate`         | ❌  | string | 終了日。形式: YYYY-MM-DD       |
| `startDate`       | ✅  | string | 開始日。形式: YYYY-MM-DD       |
| `timeGranularity` | ❌  | string | 時間の粒度 (hour/day/month)   |

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/chatbots/summary/?endDate=example&startDate=example&timeGranularity=day" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/chatbots/summary/?endDate=example&startDate=example&timeGranularity=day", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/chatbots/summary/?endDate=example&startDate=example&timeGranularity=day"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/organizations/550e8400-e29b-41d4-a716-446655440000/usage-statistics/chatbots/summary/?endDate=example&startDate=example&timeGranularity=day", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "totalInputCharacters"?: integer // 入力文字数の合計 (任意)
  "totalOutputCharacters"?: integer // 出力文字数の合計 (任意)
  "totalCharacters"?: integer // 文字数の合計 (任意)
  "totalInputTokens"?: integer // 入力トークン数の合計 (任意)
  "totalOutputTokens"?: integer // 出力トークン数の合計 (任意)
  "totalTokens"?: integer // トークン数の合計 (任意)
  "totalMessages"?: integer // メッセージ数の合計 (任意)
  "totalConversations"?: integer // 会話数の合計 (任意)
  "chatbotScope"?: string (enum: organization, accessible_chatbots) // 呼び出し元の利用統計の対象範囲です。organization＝組織全体、accessible_chatbots＝呼び出し元が属するロールで利用を許可された AI アシスタントのみです (任意)
  "totalChatbots"?: integer // クエリ対象期間内に利用記録がある AI アシスタントの数（重複を除く）です。期間内に利用されていないものは含まず、組織の AI アシスタント総数ではありません (任意)
}
```

**レスポンスの値の例**

```json
{
  "totalInputCharacters": 456,
  "totalOutputCharacters": 456,
  "totalCharacters": 456,
  "totalInputTokens": 456,
  "totalOutputTokens": 456,
  "totalTokens": 456,
  "totalMessages": 456,
  "totalConversations": 456,
  "chatbotScope": "organization",
  "totalChatbots": 456
}
```

***

### 自分のメモリを一覧表示 <a href="#me-memories-list" id="me-memories-list"></a>

GET `/api/v1/me/memories/`

{% hint style="info" %}
`X-Organization-Id` ヘッダーで操作対象の組織を指定してください。API キーで呼び出す場合も必要です。`status`（`active`／`expired`）と `kind`（`fact`／`preference`／`instruction`）のクエリパラメーターで絞り込めます。確認待ちや拒否されたメモリは表示されません。動作の詳細は、技術マニュアルの[メンバーメモリ管理 API](https://docs.maiagent.ai/tech/api-integration/endpoint-behaviors/member-memory-api)をご覧ください。
{% endhint %}

#### パラメーター

| パラメーター名    | 必須 | 型       | 説明                                                                                               |
| ---------- | -- | ------- | ------------------------------------------------------------------------------------------------ |
| `kind`     | ❌  | string  | \`fact\`: 事実 ; \`preference\`: 好み ; \`instruction\`: 指示 ; \`summary\`: 要約 ; \`profile\`: プロフィール; |
| `page`     | ❌  | integer | ページ分割された結果セット内のページ番号です。                                                                          |
| `pageSize` | ❌  | integer | 1 ページあたりに返す結果の件数です。                                                                              |
| `status`   | ❌  | string  | \`pending\`: 確認待ち ; \`active\`: 有効 ; \`rejected\`: 拒否 ; \`expired\`: 期限切れ;                       |

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X GET "https://api.maiagent.ai/api/v1/me/memories/?kind=fact&page=1&pageSize=1&status=active" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

axios.get("https://api.maiagent.ai/api/v1/me/memories/?kind=fact&page=1&pageSize=1&status=active", config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = "https://api.maiagent.ai/api/v1/me/memories/?kind=fact&page=1&pageSize=1&status=active"
headers = {
    "Authorization": "Api-Key YOUR_API_KEY"
}


response = requests.get(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->get("https://api.maiagent.ai/api/v1/me/memories/?kind=fact&page=1&pageSize=1&status=active", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "count": integer
  "next"?: string (uri) // 省略可能
  "previous"?: string (uri) // 省略可能
  "results": [
    {
      "id": string (uuid)
      "topic": string // 関連するメモリをグループ化するために LLM が割り当てるトピックスラッグです（例: "language_preferences"、"role"、"communication_style"）。Null は、トピックでグループ化されていない従来のメモリを示します。
      "category": // 異なる型になる場合があります
      string (enum: personal_info, work_role, projects, communication, response_format, tools_tech, interests, health_lifestyle, schedule_plans, other) // ユーザーに表示する固定カテゴリーです。Null は、カテゴリーがない従来のメモリを示します。

* `personal_info` - 個人情報
* `work_role` - 業務と役割
* `projects` - プロジェクトと業務
* `communication` - コミュニケーションの設定
* `response_format` - レスポンス形式の設定
* `tools_tech` - ツールと技術
* `interests` - 興味と趣味
* `health_lifestyle` - 健康とライフスタイル
* `schedule_plans` - スケジュールと計画
* `other` - その他
      "categoryDisplay": string // 翻訳されたカテゴリー名です。
      "summary": string // メモリのトピックを 1 行で要約したものです。
      "details": object // このトピックに関する具体的な事実です。文字列のリストとして保存されます。
      "kind": 
      {
      }
      "source":  // このメモリの作成方法です。ユーザーによる明示的な発言、エージェントによる抽出、または手動追加を示します。

* `user_stated` - ユーザーによる発言
* `agent_extracted` - エージェントによる抽出
* `agent_stated` - エージェントによる発言
* `user_manual` - ユーザーによる手動追加
      {
      }
      "requestedByUser": boolean // ユーザーがエージェントに明示的に記憶するよう依頼した場合は True です。UI ラベル（S12）のみに影響し、LRU による削除の優先順位（S6）には影響しません。
      "status": 
      {
      }
      "createdAt": string (timestamp)
      "updatedAt": string (timestamp)
    }
  ]
}
```

**レスポンス値の例**

```json
{
  "count": 123,
  "next": "http://api.example.org/accounts/?page=4",
  "previous": "http://api.example.org/accounts/?page=2",
  "results": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "topic": "レスポンス文字列",
      "category": "personal_info",
      "categoryDisplay": "レスポンス文字列",
      "summary": "レスポンス文字列",
      "details": null,
      "kind": {},
      "source": {},
      "requestedByUser": false,
      "status": {},
      "createdAt": "レスポンス文字列",
      "updatedAt": "レスポンス文字列"
    }
  ]
}
```

***

### 自分のメモリを作成または更新 <a href="#me-memories-create" id="me-memories-create"></a>

POST `/api/v1/me/memories/`

{% hint style="info" %}
`X-Organization-Id` ヘッダーで操作対象の組織を指定してください。API キーで呼び出す場合も必要です。リクエストフィールドは、`topic`（必須、最大 100 文字、小文字の英字、数字、およびそれらの間のアンダースコアのみ使用可能）、`summary`（必須、最大 500 文字）、`details`（必須、文字列の配列、最大 20 項目、各項目は最大 500 文字）、`kind`（`fact`／`preference`／`instruction`、デフォルトは `fact`）です。同じメンバーに同じ `topic` の有効なメモリがある場合は、そのメモリを更新して 200 を返します。新規作成時は 201 を返します。
{% endhint %}

#### リクエストボディ

**リクエストパラメーター**

| フィールド    | 型                                                                                                                                                       | 必須  | 説明                                                                                                                                                   |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| topic    | string                                                                                                                                                  | はい  |                                                                                                                                                      |
| category | string (enum: personal\_info, work\_role, projects, communication, response\_format, tools\_tech, interests, health\_lifestyle, schedule\_plans, other) | いいえ | `personal_info`: 個人情報 ; `work_role`: 業務と役割 ; `projects`: プロジェクトと業務 ; `communication`: コミュニケーションの設定 ; `response_format`: レスポンス形式の設定 ; `tools_tech`... |
| summary  | string                                                                                                                                                  | はい  |                                                                                                                                                      |
| details  | array\[string]                                                                                                                                          | はい  |                                                                                                                                                      |
| kind     | object                                                                                                                                                  | いいえ |                                                                                                                                                      |

**リクエストスキーマの例**

```typescript
{
  "topic": string
  "category"?: string (enum: personal_info, work_role, projects, communication, response_format, tools_tech, interests, health_lifestyle, schedule_plans, other) // * `personal_info` - 個人情報
* `work_role` - 業務と役割
* `projects` - プロジェクトと業務
* `communication` - コミュニケーションの設定
* `response_format` - レスポンス形式の設定
* `tools_tech` - ツールと技術
* `interests` - 興味と趣味
* `health_lifestyle` - 健康とライフスタイル
* `schedule_plans` - スケジュールと計画
* `other` - その他 (省略可能)
  "summary": string
  "details": [
    string
  ]
  "kind"?:  // 省略可能
  {
  }
}
```

**リクエスト値の例**

```json
{
  "topic": "サンプル文字列",
  "category": "personal_info",
  "summary": "サンプル文字列",
  "details": [
    "サンプル文字列"
  ],
  "kind": {}
}
```

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X POST "https://api.maiagent.ai/api/v1/me/memories/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "topic": "サンプル文字列",
    "category": "personal_info",
    "summary": "サンプル文字列",
    "details": [
      "サンプル文字列"
    ],
    "kind": {}
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "topic": "サンプル文字列",
    "category": "personal_info",
    "summary": "サンプル文字列",
    "details": [
      "サンプル文字列"
    ],
    "kind": {}
  };

axios.post("https://api.maiagent.ai/api/v1/me/memories/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "topic": "サンプル文字列",
    "category": "personal_info",
    "summary": "サンプル文字列",
    "details": [
        "サンプル文字列"
    ],
    "kind": {}
}

response = requests.post(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->post("https://api.maiagent.ai/api/v1/me/memories/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'topic' => 'サンプル文字列',
            'category' => 'personal_info',
            'summary' => 'サンプル文字列',
            'details' => [
                'サンプル文字列'
            ],
            'kind' => new \stdClass()
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンスボディ

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "topic": string // 関連するメモリをグループ化するために LLM が割り当てるトピックスラッグです（例: "language_preferences"、"role"、"communication_style"）。Null は、トピックでグループ化されていない従来のメモリを示します。
  "category": // 異なる型になる場合があります
  string (enum: personal_info, work_role, projects, communication, response_format, tools_tech, interests, health_lifestyle, schedule_plans, other) // ユーザーに表示する固定カテゴリーです。Null は、カテゴリーがない従来のメモリを示します。

* `personal_info` - 個人情報
* `work_role` - 業務と役割
* `projects` - プロジェクトと業務
* `communication` - コミュニケーションの設定
* `response_format` - レスポンス形式の設定
* `tools_tech` - ツールと技術
* `interests` - 興味と趣味
* `health_lifestyle` - 健康とライフスタイル
* `schedule_plans` - スケジュールと計画
* `other` - その他
  "categoryDisplay": string // 翻訳されたカテゴリー名です。
  "summary": string // メモリのトピックを 1 行で要約したものです。
  "details": object // このトピックに関する具体的な事実です。文字列のリストとして保存されます。
  "kind": 
  {
  }
  "source":  // このメモリの作成方法です。ユーザーによる明示的な発言、エージェントによる抽出、または手動追加を示します。

* `user_stated` - ユーザーによる発言
* `agent_extracted` - エージェントによる抽出
* `agent_stated` - エージェントによる発言
* `user_manual` - ユーザーによる手動追加
  {
  }
  "requestedByUser": boolean // ユーザーがエージェントに明示的に記憶するよう依頼した場合は True です。UI ラベル（S12）のみに影響し、LRU による削除の優先順位（S6）には影響しません。
  "status": 
  {
  }
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "topic": "レスポンス文字列",
  "category": "personal_info",
  "categoryDisplay": "レスポンス文字列",
  "summary": "レスポンス文字列",
  "details": null,
  "kind": {},
  "source": {},
  "requestedByUser": false,
  "status": {},
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

**ステータスコード: 201**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "topic": string // 関連するメモリをグループ化するために LLM が割り当てるトピックスラッグです（例: "language_preferences"、"role"、"communication_style"）。Null は、トピックでグループ化されていない従来のメモリを示します。
  "category": // 異なる型になる場合があります
  string (enum: personal_info, work_role, projects, communication, response_format, tools_tech, interests, health_lifestyle, schedule_plans, other) // ユーザーに表示する固定カテゴリーです。Null は、カテゴリーがない従来のメモリを示します。

* `personal_info` - 個人情報
* `work_role` - 業務と役割
* `projects` - プロジェクトと業務
* `communication` - コミュニケーションの設定
* `response_format` - レスポンス形式の設定
* `tools_tech` - ツールと技術
* `interests` - 興味と趣味
* `health_lifestyle` - 健康とライフスタイル
* `schedule_plans` - スケジュールと計画
* `other` - その他
  "categoryDisplay": string // 翻訳されたカテゴリー名です。
  "summary": string // メモリのトピックを 1 行で要約したものです。
  "details": object // このトピックに関する具体的な事実です。文字列のリストとして保存されます。
  "kind": 
  {
  }
  "source":  // このメモリの作成方法です。ユーザーによる明示的な発言、エージェントによる抽出、または手動追加を示します。

* `user_stated` - ユーザーによる発言
* `agent_extracted` - エージェントによる抽出
* `agent_stated` - エージェントによる発言
* `user_manual` - ユーザーによる手動追加
  {
  }
  "requestedByUser": boolean // ユーザーがエージェントに明示的に記憶するよう依頼した場合は True です。UI ラベル（S12）のみに影響し、LRU による削除の優先順位（S6）には影響しません。
  "status": 
  {
  }
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "topic": "レスポンス文字列",
  "category": "personal_info",
  "categoryDisplay": "レスポンス文字列",
  "summary": "レスポンス文字列",
  "details": null,
  "kind": {},
  "source": {},
  "requestedByUser": false,
  "status": {},
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### 自分のメモリを変更または再有効化 <a href="#me-memories-partial-update" id="me-memories-partial-update"></a>

PATCH `/api/v1/me/memories/{id}/`

{% hint style="info" %}
`X-Organization-Id` ヘッダーで操作対象の組織を指定してください。API キーで呼び出す場合も必要です。`topic`、`summary`、`details`（制限は作成時と同じです）で内容を変更するか、`status`（`active`／`expired`）で無効化または再有効化できます。少なくとも 1 つのフィールドを指定してください。
{% endhint %}

#### パラメーター

| パラメーター名 | 必須 | 型      | 説明                          |
| ------- | -- | ------ | --------------------------- |
| `id`    | ✅  | string | このメモリエントリーを識別する UUID 文字列です。 |

#### リクエストボディ

**リクエストパラメーター**

| フィールド    | 型                                                                                                                                                       | 必須  | 説明                                                                                                                                                   |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| topic    | string                                                                                                                                                  | いいえ |                                                                                                                                                      |
| category | string (enum: personal\_info, work\_role, projects, communication, response\_format, tools\_tech, interests, health\_lifestyle, schedule\_plans, other) | いいえ | `personal_info`: 個人情報 ; `work_role`: 業務と役割 ; `projects`: プロジェクトと業務 ; `communication`: コミュニケーションの設定 ; `response_format`: レスポンス形式の設定 ; `tools_tech`... |
| summary  | string                                                                                                                                                  | いいえ |                                                                                                                                                      |
| details  | array\[string]                                                                                                                                          | いいえ |                                                                                                                                                      |
| status   | string (enum: active, expired)                                                                                                                          | いいえ | `active`: 有効 ; `expired`: 期限切れ;                                                                                                                      |

**リクエストスキーマの例**

```typescript
{
  "topic"?: string // 省略可能
  "category"?: string (enum: personal_info, work_role, projects, communication, response_format, tools_tech, interests, health_lifestyle, schedule_plans, other) // * `personal_info` - 個人情報
* `work_role` - 業務と役割
* `projects` - プロジェクトと業務
* `communication` - コミュニケーションの設定
* `response_format` - レスポンス形式の設定
* `tools_tech` - ツールと技術
* `interests` - 興味と趣味
* `health_lifestyle` - 健康とライフスタイル
* `schedule_plans` - スケジュールと計画
* `other` - その他 (省略可能)
  "summary"?: string // 省略可能
  "details"?: [ // 省略可能
    string
  ]
  "status"?: string (enum: active, expired) // * `active` - 有効
* `expired` - 期限切れ (省略可能)
}
```

**リクエスト値の例**

```json
{
  "topic": "サンプル文字列",
  "category": "personal_info",
  "summary": "サンプル文字列",
  "details": [
    "サンプル文字列"
  ],
  "status": "active"
}
```

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X PATCH "https://api.maiagent.ai/api/v1/me/memories/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "topic": "サンプル文字列",
    "category": "personal_info",
    "summary": "サンプル文字列",
    "details": [
      "サンプル文字列"
    ],
    "status": "active"
  }'

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY',
    'Content-Type': 'application/json'
  }
};

// リクエストボディ (payload)
const data = {
    "topic": "サンプル文字列",
    "category": "personal_info",
    "summary": "サンプル文字列",
    "details": [
      "サンプル文字列"
    ],
    "status": "active"
  };

axios.patch("https://api.maiagent.ai/api/v1/me/memories/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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

# リクエストボディ (payload)
data = {
    "topic": "サンプル文字列",
    "category": "personal_info",
    "summary": "サンプル文字列",
    "details": [
        "サンプル文字列"
    ],
    "status": "active"
}

response = requests.patch(url, json=data, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->patch("https://api.maiagent.ai/api/v1/me/memories/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY',
            'Content-Type' => 'application/json'
        ],
        'json' => [
            'topic' => 'サンプル文字列',
            'category' => 'personal_info',
            'summary' => 'サンプル文字列',
            'details' => [
                'サンプル文字列'
            ],
            'status' => 'active'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

**ステータスコード: 200**

**レスポンススキーマの例**

```typescript
{
  "id": string (uuid)
  "topic": string // LLM-assigned topic slug for grouping related memories (e.g. "language_preferences", "role", "communication_style"). Null means legacy memory without topic grouping.
  "category": // 異なる型を取り得ます
  string (enum: personal_info, work_role, projects, communication, response_format, tools_tech, interests, health_lifestyle, schedule_plans, other) // Fixed category shown to users. Null means legacy memory without a category.

* `personal_info` - Personal Info
* `work_role` - Work and Role
* `projects` - Projects and Work
* `communication` - Communication Preferences
* `response_format` - Response Format Preferences
* `tools_tech` - Tools and Technology
* `interests` - Interests and Hobbies
* `health_lifestyle` - Health and Lifestyle
* `schedule_plans` - Schedule and Plans
* `other` - Other
  "categoryDisplay": string // Translated category name.
  "summary": string // One-line summary of the memory topic.
  "details": object // Concrete facts for this topic, stored as a list of strings.
  "kind": 
  {
  }
  "source":  // How this memory was created: user explicitly stated, agent extracted, or manually added.

* `user_stated` - User Stated
* `agent_extracted` - Agent Extracted
* `agent_stated` - Agent Stated
* `user_manual` - User Manual
  {
  }
  "requestedByUser": boolean // True when the user explicitly asked the agent to remember this. Only affects the UI label (S12), not LRU eviction priority (S6).
  "status": 
  {
  }
  "createdAt": string (timestamp)
  "updatedAt": string (timestamp)
}
```

**レスポンス値の例**

```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "topic": "レスポンス文字列",
  "category": "personal_info",
  "categoryDisplay": "レスポンス文字列",
  "summary": "レスポンス文字列",
  "details": null,
  "kind": {},
  "source": {},
  "requestedByUser": false,
  "status": {},
  "createdAt": "レスポンス文字列",
  "updatedAt": "レスポンス文字列"
}
```

***

### 自分のメモリを削除 <a href="#me-memories-destroy" id="me-memories-destroy"></a>

DELETE `/api/v1/me/memories/{id}/`

{% hint style="info" %}
`X-Organization-Id` ヘッダーを含めて操作対象の組織を指定してください。API キーを使用して呼び出す場合も、このヘッダーが必要です。
{% endhint %}

#### パラメータ

| パラメータ名 | 必須 | 型      | 説明                                           |
| ------ | -- | ------ | -------------------------------------------- |
| `id`   | ✅  | string | A UUID string identifying this Memory Entry. |

#### コード例

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

```bash
# API 呼び出し例 (Shell)
curl -X DELETE "https://api.maiagent.ai/api/v1/me/memories/550e8400-e29b-41d4-a716-446655440000/" \
  -H "Authorization: Api-Key YOUR_API_KEY"

# 実行前に YOUR_API_KEY を置き換え、リクエストデータを確認してください。
```

{% endtab %}

{% tab title="JavaScript" %}

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

// リクエストヘッダーを設定します
const config = {
  headers: {
    'Authorization': 'Api-Key YOUR_API_KEY'
  }
};

// リクエストボディ (payload)
const data = null;

axios.delete("https://api.maiagent.ai/api/v1/me/memories/550e8400-e29b-41d4-a716-446655440000/", data, config)
  .then(response => {
    console.log('レスポンスを正常に取得しました:');
    console.log(response.data);
  })
  .catch(error => {
    console.error('リクエストでエラーが発生しました:');
    console.error(error.response?.data || error.message);
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

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


response = requests.delete(url, headers=headers)
try:
    print("レスポンスを正常に取得しました:")
    print(response.json())
except Exception as e:
    print("リクエストでエラーが発生しました:", e)
```

{% endtab %}

{% tab title="PHP" %}

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

$client = new GuzzleHttp\Client();

try {
    $response = $client->delete("https://api.maiagent.ai/api/v1/me/memories/550e8400-e29b-41d4-a716-446655440000/", [
        'headers' => [
            'Authorization' => 'Api-Key YOUR_API_KEY'
        ]
    ]);
    
    $data = json_decode($response->getBody(), true);
    echo "レスポンスを正常に取得しました:\n";
    print_r($data);
} catch (Exception $e) {
    echo 'リクエストでエラーが発生しました: ' . $e->getMessage();
}
?>
```

{% endtab %}
{% endtabs %}

#### レスポンス内容

| ステータスコード | 説明               |
| -------- | ---------------- |
| 204      | No response body |

***


---

# 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/ja/api-reference/zu-zhi-he-cheng-yuan.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.
