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

# OpenAI Chat Completions API 사용

> 전체 request URL, Bearer API Key, curl, Python 및 JavaScript examples와 함께 BetterToken의 OpenAI-compatible Chat Completions API를 사용하세요.

`POST https://www.bettertoken.ai/v1/chat/completions`로 OpenAI-compatible Chat Completions를 호출하세요. 대부분의 external tools는 Base URL `https://www.bettertoken.ai/v1`을 사용하고 `/chat/completions`를 자체적으로 추가합니다.

## 주요 설정

| 필드               | 값                                                |
| ---------------- | ------------------------------------------------ |
| API Key          | BetterToken API Key                              |
| Full request URL | `https://www.bettertoken.ai/v1/chat/completions` |
| Model            | `YOUR_MODEL_ID`                                  |

## 사전 요구 사항

* <a href={"https://bettertoken.ai/register"}>BetterToken API Key 만들기</a>
* <a href={"https://bettertoken.ai/pricing"}>모델 광장</a> 또는 key **Setup** dialog에서 Model ID 복사
* `curl` 또는 Python 3 / Node.js가 있는 terminal 준비

## 설치

<Tabs>
  <Tab title="curl">
    `curl`에는 SDK가 필요하지 않습니다. terminal에서 `curl --version`이 작동하는지 확인하세요.
  </Tab>

  <Tab title="Python">
    ```bash theme={null}
    python -m pip install openai
    ```
  </Tab>

  <Tab title="JavaScript">
    ```bash theme={null}
    npm install openai
    ```
  </Tab>
</Tabs>

## 수동 설정

### curl

```bash theme={null}
curl "https://www.bettertoken.ai/v1/chat/completions" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  --data '{
    "model": "YOUR_MODEL_ID",
    "messages": [
      {
        "role": "user",
        "content": "Hello"
      }
    ]
  }'
```

### Python SDK

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

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://www.bettertoken.ai/v1",
)

response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[
        {"role": "user", "content": "Hello"},
    ],
)

print(response.choices[0].message.content)
```

### JavaScript SDK

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

const client = new OpenAI({
  apiKey: "YOUR_API_KEY",
  baseURL: "https://www.bettertoken.ai/v1",
});

const response = await client.chat.completions.create({
  model: "YOUR_MODEL_ID",
  messages: [{ role: "user", content: "Hello" }],
});

console.log(response.choices[0].message.content);
```

## 연결 확인

오른쪽 Playground에서 다음을 수행하세요.

1. **Authorization** 아래에 `YOUR_API_KEY`를 입력하세요.
2. `model`을 `YOUR_MODEL_ID`로 바꾸세요.
3. `messages`를 수정하고 request를 보내세요.

Playground는 이미 전체 URL `https://www.bettertoken.ai/v1/chat/completions`을 사용합니다.

`200` response에 `choices[0].message.content`의 model output이 포함되면 연결이 확인됩니다.

## 모델 전환

`YOUR_MODEL_ID`를 모델 광장 또는 **Setup** dialog의 전체 Model ID로 바꾸세요. display name을 기준으로 Model ID를 줄이지 마세요.

## 자주 발생하는 오류

| 오류              | 해결 방법                                                                                                                             |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `401`           | `Authorization: Bearer YOUR_API_KEY`를 확인한 다음 BetterToken API Key를 다시 복사하세요.                                                       |
| `404`           | direct HTTP calls는 `https://www.bettertoken.ai/v1/chat/completions`을 사용하며 SDK `base_url`은 `https://www.bettertoken.ai/v1`을 사용합니다. |
| Model not found | 모델 광장 또는 **Setup** dialog의 전체 Model ID를 사용하세요.                                                                                    |
| Invalid request | `messages`가 array이고 모든 item에 `role`과 `content`가 있는지 확인하세요.                                                                        |

## 고급 설정

### 지원 Provider

| Provider | 상태      |
| -------- | ------- |
| Claude   | 지원되지 않음 |
| GPT      | 수동 설정   |
| Kimi     | 수동 설정   |
| GLM      | 수동 설정   |

<Note>표시된 상태는 이 페이지에서 설명하는 BetterToken 설정 방식에 적용됩니다.</Note>

<Accordion title="설정 방식 설명">
  * **수동 설정**: API Key, Base URL, Model을 입력하세요.
  * **지원되지 않음**: 검증된 직접 연결 방식이 아직 없습니다.
</Accordion>

## 기술 세부 정보

<Accordion title="Base URL 및 전체 request URL">
  GitHub Copilot 및 TRAE처럼 전체 request URL이 필요한 tools는 `https://www.bettertoken.ai/v1/chat/completions`을 사용합니다. Cursor, Cline, OpenCode, n8n 및 Dify처럼 path를 자체적으로 추가하는 tools는 `https://www.bettertoken.ai/v1`만 사용합니다.
</Accordion>


## OpenAPI

````yaml api-reference/openapi.json POST /v1/chat/completions
openapi: 3.1.0
info:
  title: BetterToken GPT Image 2 API
  description: >-
    OpenAI-compatible image generation and image editing endpoints for
    BetterToken.
  version: 1.0.0
servers:
  - url: https://www.bettertoken.ai
security:
  - bearerAuth: []
paths:
  /v1/chat/completions:
    post:
      tags:
        - OpenAI Chat Completions
      summary: 创建 Chat Completions 响应
      description: >-
        通过 BetterToken 的 OpenAI-compatible Chat Completions API 向 GPT
        提供商模型发送对话消息。适用于需要 /v1/chat/completions 的外部工具和应用。
      operationId: createChatCompletion
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChatCompletionsRequest'
            example:
              model: YOUR_MODEL_ID
              messages:
                - role: user
                  content: Hello
      responses:
        '200':
          $ref: '#/components/responses/ChatCompletionResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '402':
          $ref: '#/components/responses/PaymentRequired'
        '429':
          $ref: '#/components/responses/RateLimited'
        '500':
          $ref: '#/components/responses/ServerError'
      x-codeSamples:
        - lang: cURL
          label: cURL
          source: |-
            curl 'https://www.bettertoken.ai/v1/chat/completions' \
              -H 'Authorization: Bearer YOUR_API_KEY' \
              -H 'Content-Type: application/json' \
              --data '{
                "model": "YOUR_MODEL_ID",
                "messages": [{"role": "user", "content": "Hello"}]
              }'
components:
  schemas:
    ChatCompletionsRequest:
      type: object
      required:
        - model
        - messages
      properties:
        model:
          type: string
          description: GPT 提供商中可用的模型 ID。请以模型广场当前显示的模型为准。
          example: YOUR_MODEL_ID
        messages:
          type: array
          minItems: 1
          description: 对话消息数组。每项应包含 role 和 content。
          items:
            type: object
            required:
              - role
              - content
            properties:
              role:
                type: string
                example: user
              content:
                type: string
                example: Hello
            additionalProperties: true
        stream:
          type: boolean
          description: 是否请求流式响应。
          default: false
      additionalProperties: true
    ChatCompletionResponse:
      type: object
      description: OpenAI-compatible Chat Completions API 响应。实际字段会随所选模型和请求参数变化。
      additionalProperties: true
    ErrorResponse:
      type: object
      properties:
        error:
          type: object
          properties:
            message:
              type: string
              example: invalid request
            type:
              type: string
              example: invalid_request_error
            code:
              type: string
              example: invalid_request
          additionalProperties: true
        message:
          type: string
          example: insufficient quota
      additionalProperties: true
  responses:
    ChatCompletionResponse:
      description: GPT 提供商模型返回的 Chat Completions API 响应。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ChatCompletionResponse'
    BadRequest:
      description: 请求格式错误、缺少参数、JSON 或 multipart 解析失败、尺寸格式错误。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Unauthorized:
      description: API Key 缺失或无效。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    PaymentRequired:
      description: 额度或余额不足。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    RateLimited:
      description: 触发限速、并发限制或上游繁忙。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    ServerError:
      description: 网关或上游服务异常。
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: BetterToken API Key
      description: >-
        Use your BetterToken API Key as a bearer token. Do not expose API keys
        in frontend browser code, screenshots, logs, tickets, or Git
        repositories.

````