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

> 使用 BetterToken OpenAI-compatible Chat Completions API：完整请求 URL、Bearer API Key、curl、Python 和 JavaScript 示例。

通过 `POST https://www.bettertoken.ai/v1/chat/completions` 调用 OpenAI-compatible Chat Completions。外部工具通常只填写 Base URL `https://www.bettertoken.ai/v1`，由工具自行追加 `/chat/completions`。

## 重点信息

| 字段       | 填写内容                                             |
| -------- | ------------------------------------------------ |
| API Key  | BetterToken API Key                              |
| 完整请求 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>或 Console 中对应 Key 的 **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 使用完整路径 `https://www.bettertoken.ai/v1/chat/completions`，无需手动拼接 endpoint。

收到 `200` 响应且 `choices[0].message.content` 包含模型回复，即表示连接成功。

## 切换模型

把请求中的 `YOUR_MODEL_ID` 替换为模型广场或 **Setup** 弹窗中的完整 Model ID。不要根据展示名称自行缩写 Model ID。

## 常见错误

| 错误     | 处理方式                                                                                                               |
| ------ | ------------------------------------------------------------------------------------------------------------------ |
| `401`  | 检查 `Authorization` 是否为 `Bearer YOUR_API_KEY`，并重新复制 BetterToken API Key。                                            |
| `404`  | 直接调用使用完整 URL `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.

````