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

# Log S2S Session Duration

> 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


# Log S2S Session Duration

Log the duration of a completed Speech-to-Speech session and deduct the time from the user's S2S time quota.

## Endpoint

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

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

## Authentication

Required: API Key

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

## Request Body

| Parameter    | Type    | Required | Description                                                 |
| ------------ | ------- | -------- | ----------------------------------------------------------- |
| `durationMs` | integer | Yes      | Session duration in milliseconds (minimum: 0)               |
| `user_id`    | string  | No       | User ID to bill this session to (defaults to API key owner) |

## Request Example

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

```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'])
```

## Response

### Success Response (200)

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

### Response Fields

| Field        | Type    | Description                         |
| ------------ | ------- | ----------------------------------- |
| `success`    | boolean | Always true for successful requests |
| `message`    | string  | Success message                     |
| `request_id` | string  | Request ID for tracking             |

## Error Responses

### 400 Bad Request

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

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

### 500 Internal Server Error

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

## Notes

* Call this endpoint after each S2S session ends to accurately track usage
* Duration should be calculated from when the WebRTC connection is established until it's closed
* Time is automatically converted from milliseconds to minutes and deducted from the user's quota
* The `user_id` parameter allows billing to a different user account
* Activity logs are automatically created for audit purposes
* Ensure you have sufficient remaining time before starting a session (check with `/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`

````