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

# S2S セッション期間をログに記録する

> Log the duration of a completed Speech-to-Speech session and deduct the time from the user's
S2S time quota. This should be called after a session ends to track usage accurately.

**Usage Tracking:**
- Duration is specified in milliseconds
- Automatically converted to minutes and deducted from user's quota
- Time is tracked per-user based on license tier
- Activity logs are created for audit purposes


# S2S セッション期間をログに記録します

完了した Speech-to-Speech セッションの継続時間を記録し、その時間をユーザーの S2S 時間割り当てから差し引きます。

## エンドポイント

```
POST /speech/s2s/log-session
```

## 説明

完了した Speech-to-Speech セッションの継続時間を記録し、その時間をユーザーの S2S 時間割り当てから差し引きます。使用状況を正確に追跡するには、セッションの終了後にこれを呼び出す必要があります。

### 使用状況の追跡

* 期間はミリ秒単位で指定します
* 自動的に分に変換され、ユーザーの割り当てから差し引かれます
* 時間はライセンス層に基づいてユーザーごとに追跡されます
* アクティビティ ログは監査目的で作成されます。

## 認証

必須: API キー

```bash theme={null}
Authorization: Bearer sk-your-api-key-here
```

## リクエスト本文

| パラメータ        | タイプ | 必須  | 説明                                       |
| ------------ | --- | --- | ---------------------------------------- |
| `durationMs` | 整数  | はい  | ミリ秒単位のセッション継続時間 (最小: 0)                  |
| `user_id`    | 文字列 | いいえ | このセッションの請求先となるユーザー ID (デフォルトは API キー所有者) |

## リクエストの例

```bash theme={null}
curl -X POST "https://{customer.name}.hiperai.ai/api/external/speech/s2s/log-session" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "durationMs": 42624,
    "user_id": "60a7c8f5e8b4f5001f7a8c23"
  }'
```

### JavaScript/Node.js

```javascript theme={null}
// Calculate session duration in milliseconds
const sessionStartTime = Date.now();
// ... session happens ...
const sessionEndTime = Date.now();
const durationMs = sessionEndTime - sessionStartTime;

const response = await fetch('https://{customer.name}.hiperai.ai/api/external/speech/s2s/log-session', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk-your-api-key-here',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    durationMs: durationMs,
    user_id: '60a7c8f5e8b4f5001f7a8c23'
  })
});

const data = await response.json();
console.log('Session logged:', data.message);
```

### パイソン

```python theme={null}
import requests
import time

# Calculate session duration
session_start = time.time() * 1000  # Convert to milliseconds
# ... session happens ...
session_end = time.time() * 1000
duration_ms = int(session_end - session_start)

url = "https://{customer.name}.hiperai.ai/api/external/speech/s2s/log-session"
headers = {
    "Authorization": "Bearer sk-your-api-key-here",
    "Content-Type": "application/json"
}
data = {
    "durationMs": duration_ms,
    "user_id": "60a7c8f5e8b4f5001f7a8c23"
}

response = requests.post(url, headers=headers, json=data)
result = response.json()
print('Session logged:', result['message'])
```

## 応答

### 成功の応答 (200)

```json theme={null}
{
  "success": true,
  "message": "S2S session logged successfully",
  "request_id": "3fb8d444-2242-4764-9202-8e9e72464192"
}
```

### 応答フィールド

| フィールド        | タイプ  | 説明                   |
| ------------ | ---- | -------------------- |
| `success`    | ブール値 | リクエストが成功した場合は常に true |
| `message`    | 文字列  | 成功メッセージ              |
| `request_id` | 文字列  | 追跡用のリクエスト ID         |

## エラー応答

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

```json theme={null}
{
  "success": false,
  "error": "Invalid user_id",
  "message": "The specified user_id does not exist",
  "request_id": "3fb8d444-2242-4764-9202-8e9e72464192"
}
```

### 401 不正

```json theme={null}
{
  "success": false,
  "error": "Invalid API key",
  "message": "The provided API key is invalid or has been revoked"
}
```

### 500 内部サーバーエラー

```json theme={null}
{
  "success": false,
  "error": "Failed to log S2S session",
  "message": "An error occurred while logging the session",
  "request_id": "3fb8d444-2242-4764-9202-8e9e72464192"
}
```

## 注意事項

* 使用状況を正確に追跡するために、各 S2S セッションの終了後にこのエンドポイントを呼び出します
* 期間は、WebRTC 接続が確立されてから閉じられるまで計算する必要があります。
* 時間は自動的にミリ秒から分に変換され、ユーザーの割り当てから差し引かれます。
* `user_id` パラメータにより、別のユーザー アカウントへの請求が可能になります
* 監査目的でアクティビティ ログが自動的に作成されます
* セッションを開始する前に十分な時間が残っていることを確認してください (`/speech/s2s/status` で確認してください)


## OpenAPI

````yaml POST /speech/s2s/log-session
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:
  /speech/s2s/log-session:
    post:
      tags:
        - Speech
      summary: Log S2S Session Duration
      description: >
        Log the duration of a completed Speech-to-Speech session and deduct the
        time from the user's

        S2S time quota. This should be called after a session ends to track
        usage accurately.


        **Usage Tracking:**

        - Duration is specified in milliseconds

        - Automatically converted to minutes and deducted from user's quota

        - Time is tracked per-user based on license tier

        - Activity logs are created for audit purposes
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                durationMs:
                  type: integer
                  description: Session duration in milliseconds
                  minimum: 0
                  example: 42624
                user_id:
                  type: string
                  description: >-
                    Optional user ID to bill this session to (defaults to API
                    key owner)
                  example: 60a7c8f5e8b4f5001f7a8c23
      responses:
        '200':
          description: Session logged successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  message:
                    type: string
                    example: S2S session logged successfully
                  request_id:
                    type: string
                    description: Request ID for tracking
                    example: 3fb8d444-2242-4764-9202-8e9e72464192
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                success: false
                error: Invalid user_id
                message: The specified user_id does not exist
                request_id: 3fb8d444-2242-4764-9202-8e9e72464192
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                success: false
                error: Failed to log S2S session
                message: An error occurred while logging the session
                request_id: 3fb8d444-2242-4764-9202-8e9e72464192
      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`

````