> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hiperai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# ロールの作成

> 新しいユーザー役割を作成する

# ロールの作成

特定の権限を持つ新しいカスタム ユーザー ロールを作成します。

## エンドポイント

```
POST /roles
```

## 説明

このエンドポイントにより、管理者は新しいカスタム ユーザー ロールを作成できます。カスタム ロールには、組織のニーズに合わせた特定の権限を付与できます。作成時にロール名、説明、権限を指定できます。

## 認証

**必須**: 管理者権限を持つ API キー

```
Authorization: Bearer sk-your-api-key-here
```

## リクエスト本文

| パラメータ                 | タイプ  | 必須  | 説明                                     |
| --------------------- | ---- | --- | -------------------------------------- |
| `name`                | 文字列  | はい  | ロール名 (システム識別子)                         |
| `displayName`         | 文字列  | はい  | 人間が判読できるロール名                           |
| `description`         | 文字列  | はい  | 役割の目的の説明                               |
| `hasAdminPanelAccess` | ブール値 | いいえ | ロールに管理パネルへのアクセス権があるかどうか (デフォルト: false) |
| `permissions`         | 配列   | いいえ | 権限オブジェクトの配列                            |
| `canInteractWithAI`   | ブール値 | いいえ | ロールが AI と対話できるかどうか (デフォルト: true)       |
| `canUseChat`          | ブール値 | いいえ | ロールがチャットを使用できるかどうか (デフォルト: true)       |

## リクエストの例

```json theme={null}
{
  "name": "content_editor",
  "displayName": "Content Editor",
  "description": "Role for editing and managing content",
  "hasAdminPanelAccess": false,
  "permissions": [
    {
      "section": "user-management",
      "level": "reader"
    },
    {
      "section": "index-management",
      "level": "admin"
    }
  ],
  "canInteractWithAI": true,
  "canUseChat": true
}
```

## 成功の応答

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

```json theme={null}
{
  "success": true,
  "message": "Role created successfully",
  "role": {
    "id": "60a7c8f5e8b4f5001f7a8c26",
    "name": "content_editor",
    "displayName": "Content Editor",
    "description": "Role for editing and managing content",
    "isSystem": false,
    "hasAdminPanelAccess": false,
    "permissions": [
      {
        "section": "user-management",
        "level": "reader"
      },
      {
        "section": "index-management",
        "level": "admin"
      }
    ],
    "canInteractWithAI": true,
    "canUseChat": true,
    "userCount": 0,
    "createdBy": {
      "id": "60a7c8f5e8b4f5001f7a8c24",
      "name": "John Doe",
      "email": "john@example.com"
    },
    "createdAt": "2024-01-20T15:30:00.000Z"
  }
}
```

### 応答フィールド

| フィールド                        | タイプ    | 説明                      |
| ---------------------------- | ------ | ----------------------- |
| `success`                    | ブール値   | 操作が成功したかどうかを示します。       |
| `message`                    | 文字列    | 成功メッセージ                 |
| `role`                       | オブジェクト | 作成されたロール オブジェクト         |
| `role.id`                    | 文字列    | 一意のロール識別子               |
| `role.name`                  | 文字列    | 役割名                     |
| `role.displayName`           | 文字列    | ロールの表示名                 |
| `role.description`           | 文字列    | 役割の説明                   |
| `role.isSystem`              | ブール値   | これがシステムの役割であるかどうか       |
| `role.hasAdminPanelAccess`   | ブール値   | ロールに管理パネルへのアクセス権があるかどうか |
| `role.permissions`           | 配列     | 権限オブジェクトの配列             |
| `role.permissions[].section` | 文字列    | 許可セクション                 |
| `role.permissions[].level`   | 文字列    | 許可レベル                   |
| `role.canInteractWithAI`     | ブール値   | ロールが AI と対話できるかどうか      |
| `role.canUseChat`            | ブール値   | ロールがチャットを使用できるかどうか      |
| `role.userCount`             | 整数     | このロールを持つユーザーの数          |
| `role.createdBy`             | オブジェクト | ロールを作成したユーザー            |
| `role.createdBy.id`          | 文字列    | 作成者ユーザーID               |
| `role.createdBy.name`        | 文字列    | 作成者名                    |
| `role.createdBy.email`       | 文字列    | 作成者のメールアドレス             |
| `role.createdAt`             | 文字列    | 作成タイムスタンプ               |

## 使用例

### JavaScript

```javascript theme={null}
const createRole = async (roleData) => {
  const response = await fetch('https://{customer.name}.hiperai.ai/api/external/roles', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk-your-api-key-here',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(roleData)
  });
  
  return await response.json();
};

// Example usage
const roleData = {
  name: "content_editor",
  displayName: "Content Editor",
  description: "Role for editing and managing content",
  hasAdminPanelAccess: false,
  permissions: [
    {
      section: "user-management",
      level: "reader"
    },
    {
      section: "index-management",
      level: "admin"
    }
  ],
  canInteractWithAI: true,
  canUseChat: true
};

const result = await createRole(roleData);
console.log('Created role:', result.role.id);
```

### パイソン

```python theme={null}
import requests

def create_role(role_data):
    url = "https://{customer.name}.hiperai.ai/api/external/roles"
    headers = {
        "Authorization": "Bearer sk-your-api-key-here",
        "Content-Type": "application/json"
    }
    
    response = requests.post(url, headers=headers, json=role_data)
    return response.json()

# Example usage
role_data = {
    "name": "content_editor",
    "displayName": "Content Editor",
    "description": "Role for editing and managing content",
    "hasAdminPanelAccess": False,
    "permissions": [
        {
            "section": "user-management",
            "level": "reader"
        },
        {
            "section": "index-management",
            "level": "admin"
        }
    ],
    "canInteractWithAI": True,
    "canUseChat": True
}

result = create_role(role_data)
print("Created role:", result["role"]["id"])
```

### cURL

```bash theme={null}
curl -X POST "https://{customer.name}.hiperai.ai/api/external/roles" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "content_editor",
    "displayName": "Content Editor",
    "description": "Role for editing and managing content",
    "hasAdminPanelAccess": false,
    "permissions": [
      {
        "section": "user-management",
        "level": "reader"
      },
      {
        "section": "index-management",
        "level": "admin"
      }
    ],
    "canInteractWithAI": true,
    "canUseChat": true
  }'
```

## エラー応答

### 400 不正なリクエスト

```json theme={null}
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Role name is required",
    "details": {
      "field": "name",
      "value": null
    }
  }
}
```

### 401 不正

```json theme={null}
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or missing API key"
  }
}
```

### 403 禁止

```json theme={null}
{
  "success": false,
  "error": {
    "code": "INSUFFICIENT_PERMISSIONS",
    "message": "Admin privileges required"
  }
}
```

### 409 紛争

```json theme={null}
{
  "success": false,
  "error": {
    "code": "ROLE_NAME_EXISTS",
    "message": "Role name already exists"
  }
}
```

### 429 リクエストが多すぎます

```json theme={null}
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded",
    "retryAfter": 60
  }
}
```

## 利用可能な権限セクション

| セクション              | 説明               |
| ------------------ | ---------------- |
| `home`             | ホームダッシュボードへのアクセス |
| `user-management`  | ユーザー管理操作         |
| `index-management` | インデックス管理操作       |
| `analytics`        | 分析とレポート          |
| `group-management` | グループ管理業務         |
| `integrations`     | 統合管理             |
| `services-status`  | サービスステータスの監視     |
| `settings`         | システム設定           |
| `announcements`    | お知らせ管理           |
| `smltp-security`   | SMLTP セキュリティ機能   |

## 利用可能な権限レベル

| レベル      | 説明                |
| -------- | ----------------- |
| `none`   | セクションにアクセスできません   |
| `reader` | セクションへの読み取り専用アクセス |
| `admin`  | セクションへの完全な管理アクセス  |

## 使用例

* **カスタム ロール**: 組織のニーズに合わせたロールを作成します
* **アクセス制御**: さまざまなユーザー タイプに特定の権限を定義します。
* **セキュリティ**: 最小特権アクセス原則を実装します。
* **コンプライアンス**: 規制要件を満たす役割を作成します
* **統合**: サードパーティ システム統合の役割を定義します。

## レート制限

* **デフォルト**: 1 分あたり 50 リクエスト
* **毎日**: 1 日あたり 5,000 リクエスト
* **毎月**: 毎月 150,000 件のリクエスト

## 注意事項

* **管理者のみ**: このエンドポイントには管理者権限が必要です
* **必須フィールド**: 名前、表示名、説明は必須です
* **権限の構造**: 権限はセクションとレベルのプロパティを持つオブジェクトです。
* **システム ロール**: カスタム ロールは決してシステム ロールではありません
* **フラット応答**: 応答はデータ オブジェクトの下にネストされていません
* **作成者情報**: ロールを作成した人を表示します。
* **ユーザー数**: 新しいロールの場合は 0 から始まります
* ロール名はシステム内で一意である必要があります
* ロールはユーザー割り当てにすぐに使用できるようになります


## OpenAPI

````yaml POST /roles
openapi: 3.0.3
info:
  title: SecureAI External API
  description: >
    SecureAI External API provides AI chat completion and image generation
    capabilities with knowledge base retrieval, 

    security policies, and comprehensive usage tracking. This API is designed
    for external developers 

    and integrations using API key authentication.


    ## Key Features

    - **RAG (Retrieval-Augmented Generation)**: Automatically search knowledge
    bases for relevant context

    - **Multi-Model Support**: OpenAI, Anthropic, Google, Meta, and other AI
    models

    - **Model Redundancy & Failover**: Caller-defined failover chains (primary +
    fallbacks) with per-attempt timeouts

    - **OpenAI-Compatible Endpoint**: Point any OpenAI SDK at `/api/external/v1`
    — no code changes

    - **Image Generation**: Generate and edit images using Google Gemini 2.5
    Flash Image

    - **Speech-to-Speech (S2S)**: Real-time voice conversations using OpenAI
    Realtime API with WebRTC

    - **Security Policies**: SMLTP policy enforcement, per-call Prompt Shield,
    and signed compliance receipts

    - **Usage Tracking**: Comprehensive usage monitoring, self-service quota,
    and rate limiting

    - **Knowledge Base Integration**: Access to personal and shared knowledge
    bases

    - **User Management**: Complete user, group, and role management
    capabilities

    - **Audit Logging**: Comprehensive activity and security audit logs


    ## Authentication

    All endpoints (except health check) require API key authentication using
    Bearer token:

    ```

    Authorization: Bearer sk-your-api-key-here

    ```


    ## Billing and Usage

    By default, API requests are billed to the user account that owns the API
    key. You can specify 

    a different user to bill by including the `user_id` parameter in your
    request. This allows for:

    - Multi-tenant applications with per-user billing

    - Flexible completion limit management

    - Per-user "Usage by Model" settings


    ## Rate Limits

    - Default: 60 requests per minute, 1000 requests per hour

    - Daily limits: 100 requests (configurable)

    - Monthly limits: 10,000 requests (configurable)


    ## Base URL

    ```

    https://secureai.hiperai.ai/api/external

    ```
  version: 1.1.0
  contact:
    name: SecureAI Support
    email: support@secureai.hiperai.ai
  license:
    name: Proprietary
    url: https://secureai.hiperai.ai/terms
servers:
  - url: https://secureai.hiperai.ai/api/external
    description: Production server
  - url: http://localhost:3010/api/external
    description: Development server
security:
  - ApiKeyAuth: []
tags:
  - name: System
    description: System health and status endpoints
  - name: Discovery
    description: Endpoints to discover available models, indexes, and policies
  - name: Chat
    description: AI chat completion endpoints
  - name: User Management
    description: Endpoints for managing user accounts and roles
  - name: Index Management
    description: Endpoints for managing knowledge base indexes
  - name: Group Management
    description: Endpoints for managing user groups
  - name: SMLTP Security
    description: Endpoints for managing SMLTP security policies and audit logs
  - name: Role Management
    description: Endpoints for managing user roles
  - name: Activity Logs
    description: Endpoints for retrieving activity logs
externalDocs:
  description: SecureAI Documentation
  url: https://secureai.hiperai.ai/docs
paths:
  /roles:
    post:
      tags:
        - Role Management
      summary: Create New Role
      description: |
        Create a new custom role. Only accessible by administrators.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - displayName
                - description
              properties:
                name:
                  type: string
                  description: Role name (lowercase, no spaces)
                  example: custom_role
                displayName:
                  type: string
                  description: Display name for the role
                  example: Custom Role
                description:
                  type: string
                  description: Role description
                  example: Custom role with specific permissions
                hasAdminPanelAccess:
                  type: boolean
                  default: false
                  description: Whether role has admin panel access
                  example: true
                permissions:
                  type: array
                  items:
                    type: object
                    properties:
                      section:
                        type: string
                        enum:
                          - home
                          - user-management
                          - index-management
                          - analytics
                          - group-management
                          - integrations
                          - services-status
                          - settings
                          - announcements
                          - smltp-security
                        example: user-management
                      level:
                        type: string
                        enum:
                          - none
                          - reader
                          - admin
                        example: admin
                  description: Array of permission objects
                  example:
                    - section: user-management
                      level: admin
                    - section: index-management
                      level: reader
                canInteractWithAI:
                  type: boolean
                  default: true
                  description: Whether role can interact with AI
                  example: true
                canUseChat:
                  type: boolean
                  default: true
                  description: Whether role can use chat
                  example: true
            example:
              name: custom_role
              displayName: Custom Role
              description: Custom role with specific permissions
              hasAdminPanelAccess: true
              permissions:
                - section: user-management
                  level: admin
                - section: index-management
                  level: reader
              canInteractWithAI: true
              canUseChat: true
      responses:
        '201':
          description: Role created successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  message:
                    type: string
                    example: Role created successfully
                  role:
                    type: object
                    properties:
                      id:
                        type: string
                        example: 60a7c8f5e8b4f5001f7a8c26
                      name:
                        type: string
                        example: custom_role
                      displayName:
                        type: string
                        example: Custom Role
                      description:
                        type: string
                        example: Custom role with specific permissions
                      isSystem:
                        type: boolean
                        example: false
                      hasAdminPanelAccess:
                        type: boolean
                        example: true
                      permissions:
                        type: array
                        items:
                          type: object
                          properties:
                            section:
                              type: string
                              example: user-management
                            level:
                              type: string
                              example: admin
                      canInteractWithAI:
                        type: boolean
                        example: true
                      canUseChat:
                        type: boolean
                        example: true
                      userCount:
                        type: integer
                        example: 0
                      createdBy:
                        type: object
                        properties:
                          id:
                            type: string
                            example: 60a7c8f5e8b4f5001f7a8c24
                          name:
                            type: string
                            example: John Doe
                          email:
                            type: string
                            example: john@example.com
                      createdAt:
                        type: string
                        format: date-time
                        example: '2024-01-15T10:30:00.000Z'
        '400':
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Invalid API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Access denied - admin only
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '409':
          description: Role name already exists
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - ApiKeyAuth: []
components:
  schemas:
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
          example: Invalid API key
        message:
          type: string
          example: The provided API key is invalid or has been revoked
        request_id:
          type: string
          example: req-abc123
          description: Request ID for tracking (if available)
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      description: |
        API key authentication using Bearer token format.
        Example: `Authorization: Bearer sk-your-api-key-here`

````