> ## 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 채팅 완료 화면 — SecureAI에서 모든 OpenAI SDK를 가리킵니다.

# OpenAI 호환 엔드포인트

SecureAI는 OpenAI 호환 표면을 노출하므로 코드 변경 없이 **기본 URL과 API 키만 변경하여 모든 OpenAI SDK**와 통합할 수 있습니다. 전체 SecureAI 보안 스택(API 키 인증, 모델/인덱스 허용 목록, SMLTP 정책 시행 + 권한, Prompt Shield, PII/DLP, 포인트 청구 및 [모델 중복 엔진](/ko/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`에 고정되어 있습니다. 지식 기반 검색이 필요한 경우 클래식 [채팅 완료](/ko/en/api/chat/completions) 엔드포인트를 사용하세요.
</Info>

## 인증

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

## OpenAI SDK 사용

### 파이썬 (`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"])
```

### 자바스크립트 (`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` | 모델 [redundancy](/ko/en/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`(있는 경우)는 서명된 규정 준수 [영수증](/ko/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`을 가지고 있습니다.

## 관련

* [채팅 완료](/ko/en/api/chat/completions) — 클래식 표면(RAG 추가).
* [이중화 및 장애 조치](/ko/ko/api/redundancy)
* [Prompt Shield API](/ko/ko/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`

````