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

# OpenAI互換エンドポイント

> ドロップイン OpenAI Chat Completions サーフェス — OpenAI SDK を SecureAI に向けます

# OpenAI 互換エンドポイント

SecureAI は OpenAI 互換サーフェスを公開しているため、**ベース URL と API キーのみを変更するだけで**、コードを変更することなく、任意の OpenAI SDK と統合できます。完全な SecureAI セキュリティ スタック (API キー認証、モデル/インデックス ホワイトリスト、SMLTP ポリシーの適用 + 資格、プロンプト シールド、PII/DLP、ポイント請求、[モデル冗長エンジン](/ja/en/api/redundancy)) がその下で実行されます。

## エンドポイント

```
POST /api/external/v1/chat/completions
GET  /api/external/v1/models
```

OpenAI クライアントの `base_url` を次のように指定します。

```
https://{customer.name}.hiperai.ai/api/external/v1
```

<Info>
  **知識ゼロのみ**

  このサーフェスは RAG/ナレッジ ベースをサポートしません\*\*。リクエストは `Zero-Knowledge` に固定されます。ナレッジベースの取得が必要な場合は、従来の [Chat Completion](/ja/en/api/chat/completions) エンドポイントを使用してください。
</Info>

## 認証

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

## OpenAI SDK の使用

### Python (`openai`)

```python theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="sk-your-api-key-here",
    base_url="https://{customer.name}.hiperai.ai/api/external/v1",
)

resp = client.chat.completions.create(
    model="openai/gpt-5-nano",
    messages=[{"role": "user", "content": "Hello!"}],
    # SecureAI extensions travel via extra_body
    extra_body={
        "smltp_policy": "internal",
        "fallback_models": ["anthropic/claude-sonnet-4"],
    },
)
print(resp.choices[0].message.content)
print(resp.model_extra["secureai"]["served_model"])
```

### JavaScript (`openai`)

```javascript theme={null}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'sk-your-api-key-here',
  baseURL: 'https://{customer.name}.hiperai.ai/api/external/v1',
});

const resp = await client.chat.completions.create({
  model: 'openai/gpt-5-nano',
  messages: [{ role: 'user', content: 'Hello!' }],
  // @ts-expect-error — SecureAI extension fields
  smltp_policy: 'internal',
  fallback_models: ['anthropic/claude-sonnet-4'],
});
console.log(resp.choices[0].message.content);
```

## リクエスト本文

標準の OpenAI フィールドがサポートされています。 `messages` は必須です (この面には `prompt` はありません)。 `max_completion_tokens` は `max_tokens` のエイリアスとして受け入れられます。

次の OpenAI パラメータは、そのままプロバイダに渡されます。

`tools`、`tool_choice`、`parallel_tool_calls`、`response_format`、`stop`、`top_p`、`frequency_penalty`、`presence_penalty`、`seed`、`logprobs`、`top_logprobs`、 `user`。

### SecureAI 拡張フィールド

これらを追加の本文フィールドとして送信します (OpenAI SDK の `extra_body` 経由):

| フィールド                        | 説明                                                   |
| ---------------------------- | ---------------------------------------------------- |
| `smltp_policy`               | この通話の SMLTP セキュリティ ポリシー。                             |
| `prompt_shield`              | `{ enabled?, policy? }` — 呼び出しごとのプロンプト シールド オーバーライド。 |
| `models` / `fallback_models` | モデル [冗長性](/ja/ja/api/redundancy) チェーン。               |
| `redundancy`                 | `{ timeout_ms, first_token_timeout_ms, on[] }`。      |
| `user_id`                    | 別のユーザーに請求します (管理者ゲート)。                               |

## 応答

標準の OpenAI `chat.completion` シェイプに、`secureai` 拡張オブジェクトを追加しました。

```json theme={null}
{
  "id": "chatcmpl-1a2b3c...",
  "object": "chat.completion",
  "created": 1705312200,
  "model": "anthropic/claude-sonnet-4",
  "choices": [
    { "index": 0, "message": { "role": "assistant", "content": "Hello!" }, "finish_reason": "stop" }
  ],
  "usage": { "prompt_tokens": 9, "completion_tokens": 3, "total_tokens": 12 },
  "secureai": {
    "served_model": "anthropic/claude-sonnet-4",
    "requested_model": "openai/gpt-5-nano",
    "failover": { "occurred": true, "attempts": [ ... ] },
    "smltp_policy_used": "internal",
    "smltp_policy_source": "request",
    "smltp_policy_hash": "a1b2c3...",
    "prompt_shield_policy": null,
    "smltp_bundle_id": "bnd_..."
  }
}
```

`secureai.smltp_bundle_id` (存在する場合) は、署名済みのコンプライアンス [領収書](/ja/en/api/receipts) と交換できます。

### ストリーミング

`stream: true`を設定します。フレームは、`data: [DONE]` で終了するネイティブ OpenAI `chat.completion.chunk` オブジェクトです。 `secureai` 拡張子は **最初** チャンクに付加されます。 `choices` (`tool_calls` デルタおよび `finish_reason` を含む) はそのまま通過します。

## エラー

このハンドラーからのエラーは OpenAI エンベロープを使用します。

```json theme={null}
{ "error": { "message": "you must provide a model parameter", "type": "invalid_request_error", "code": null } }
```

冗長チェーン全体に障害が発生すると、エラーは `code: "all_models_failed"` およびステータス `429` (すべてのレート制限) または `502` (それ以外) を使用します。セキュリティミドルウェアの拒否により、SecureAI `{ "success": false, ... }` の形状が維持されます。どちらも常に `message` を持ちます。

## 関連

* [チャット補完](/ja/en/api/chat/completions) — クラシック サーフェス (RAG を追加)。
* [冗長性とフェイルオーバー](/ja/ja/api/redundancy)
* [プロンプト シールド API](/ja/ja/api/threat-defense/prompt-shield)


## OpenAPI

````yaml POST /v1/chat/completions
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:
  /v1/chat/completions:
    post:
      tags:
        - Chat
      summary: OpenAI-compatible chat completion
      description: >
        Drop-in OpenAI Chat Completions surface. Point any OpenAI SDK's
        `base_url`

        at `/api/external/v1` with a SecureAI API key. Strict OpenAI
        request/response

        shapes (`choices[]`, SSE `data:` frames, `[DONE]`, tool_calls
        passthrough).

        RAG is not available here (pinned to Zero-Knowledge). SecureAI extension

        fields (`smltp_policy`, `prompt_shield`, `models`/`fallback_models`,

        `redundancy`, `user_id`) are accepted as extra body fields and echoed
        back

        in a `secureai` response object.
      operationId: openaiCompatibleChatCompletion
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - model
                - messages
              properties:
                model:
                  type: string
                  example: openai/gpt-5-nano
                messages:
                  type: array
                  items:
                    type: object
                    properties:
                      role:
                        type: string
                        enum:
                          - system
                          - user
                          - assistant
                      content:
                        type: string
                temperature:
                  type: number
                max_tokens:
                  type: integer
                stream:
                  type: boolean
                models:
                  type: array
                  items:
                    type: string
                fallback_models:
                  type: array
                  items:
                    type: string
                redundancy:
                  type: object
                  description: '{ timeout_ms, first_token_timeout_ms, on[] }'
                smltp_policy:
                  type: string
                prompt_shield:
                  type: object
                  description: '{ enabled?, policy? } per-call Prompt Shield override'
      responses:
        '200':
          description: OpenAI chat.completion object plus a `secureai` extension
        '400':
          description: Invalid request (OpenAI error envelope)
        '401':
          description: Invalid API key
        '429':
          description: Rate limited (or all models rate-limited)
        '502':
          description: All model attempts in the redundancy chain failed
      security:
        - ApiKeyAuth: []
components:
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      description: |
        API key authentication using Bearer token format.
        Example: `Authorization: Bearer sk-your-api-key-here`

````