> ## 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 を使用する

> 完全なリクエスト URL、Bearer API Key、curl、Python、JavaScript の例を使って、BetterToken の OpenAI 互換 Chat Completions API を利用します。

`POST https://www.bettertoken.ai/v1/chat/completions` で OpenAI 互換の Chat Completions を呼び出します。ほとんどの外部ツールでは 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>またはキーの **Setup** ダイアログから Model ID をコピー
* `curl` を使えるターミナル、または Python 3 / Node.js を用意

## インストール

<Tabs>
  <Tab title="curl">
    `curl` に SDK は不要です。ターミナルで `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` を編集してリクエストを送信します。

Playground では完全な URL `https://www.bettertoken.ai/v1/chat/completions` がすでに使用されています。

`200` レスポンスにモデル出力が `choices[0].message.content` として含まれていれば、接続は確認できています。

## モデルの切り替え

`YOUR_MODEL_ID` を、モデル広場または **Setup** ダイアログに表示される完全な Model ID に置き換えます。表示名をもとに Model ID を短縮しないでください。

## よくあるエラー

| エラー        | 対処方法                                                                                                                                |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `401`      | `Authorization: Bearer YOUR_API_KEY` を確認してから、BetterToken API Key をもう一度コピーします。                                                       |
| `404`      | 直接の HTTP 呼び出しには `https://www.bettertoken.ai/v1/chat/completions` を使用します。SDK の `base_url` には `https://www.bettertoken.ai/v1` を使用します。 |
| モデルが見つからない | モデル広場または **Setup** ダイアログに表示される完全な Model ID を使用します。                                                                                  |
| 無効なリクエスト   | `messages` が配列であり、各項目に `role` と `content` があることを確認します。                                                                              |

## 高度な設定

### 対応プロバイダー

| プロバイダー | 対応状況 |
| ------ | ---- |
| Claude | 未対応  |
| GPT    | 手動設定 |
| Kimi   | 手動設定 |
| GLM    | 手動設定 |

<Note>ここに示す対応状況は、このページで説明する BetterToken の設定方法に適用されます。</Note>

<Accordion title="設定方法の説明">
  * **手動設定**：API Key、Base URL、Model を入力します。
  * **未対応**：検証済みの直接接続方法はまだありません。
</Accordion>

## 技術情報

<Accordion title="Base URL と完全なリクエスト URL">
  GitHub Copilot や TRAE など、完全なリクエスト URL を必要とするツールでは `https://www.bettertoken.ai/v1/chat/completions` を使用します。Cursor、Cline、OpenCode、n8n、Dify など、パスを自ら追加するツールでは `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.

````