> ## 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・Anthropic SDK の接続ガイド

> BetterToken 用の OpenAI SDK の Base URL と Anthropic SDK の base_url を設定。Python・JavaScript・curl で API の認証と応答を確認します。

OpenAI SDK の Base URL には `https://bettertoken.ai/v1`、Anthropic SDK には `https://bettertoken.ai` を指定します。以下の例では、BetterToken API Key を使って Chat Completions、Responses、Messages に短いテキストリクエストを送信します。

## SDK と Base URL を選ぶ

| API | SDK | Base URL | 送信時の認証ヘッダー | リファレンス |
| - | - | - | - | - |
| Chat Completions | OpenAI | `https://bettertoken.ai/v1` | `Authorization: Bearer YOUR_API_KEY` | [Chat Completions リファレンス](/ja/api-reference/chat-completions.md) |
| Responses | OpenAI | `https://bettertoken.ai/v1` | `Authorization: Bearer YOUR_API_KEY` | [Responses リファレンス](/ja/api-reference/responses.md) |
| Messages | Anthropic | `https://bettertoken.ai`（`/v1` は付けない） | `x-api-key: YOUR_API_KEY` | [Messages](/ja/api-reference/messages.md) |

SDK がエンドポイントのパスと認証ヘッダーを追加します。Anthropic SDK は API バージョンのヘッダーも送信します。既存のコードを変更する場合は、[プロトコルの比較](/ja/faq/concepts/openai-compatible-vs-anthropic-compatible.md)を確認してください。

## 前提条件

[クイックスタート](/ja/quickstart.md)に従って BetterToken API Key を作成し、残高をチャージします。[モデル広場](https://bettertoken.ai/pricing)から、使用するエンドポイントで利用可能な Model ID をコピーしてください。リクエストを実行する前に、以下の二つのプレースホルダーを置き換えます。

例を実行するターミナルで次の変数を設定します。このページのシェルコマンドは macOS / Linux 用です。

```bash theme={null}
export BETTERTOKEN_API_KEY="YOUR_API_KEY"
export BETTERTOKEN_MODEL_ID="YOUR_MODEL_ID"
```

Python では、プロジェクトの仮想環境に SDK をインストールします。

```bash theme={null}
python3 -m venv .venv
source .venv/bin/activate
python -m pip install openai anthropic
```

JavaScript では、プロジェクトにパッケージをインストールします。各例を別々の `.mjs` ファイルとして保存し、`node` で実行してください。

```bash theme={null}
npm install openai @anthropic-ai/sdk
```

すべての例で `BETTERTOKEN_API_KEY` から Key を読み込みます。一度のテストが意図せず複数回の試行にならないよう、SDK の再試行を無効にしています。アプリの再試行方針は、[エラーと制限](/ja/api-reference/errors.md#retry-temporary-failures)を参照してください。

## Chat Completions を呼び出す

入力する会話には `messages` を使います。正常なテキスト応答には `choices[0].message.content` が含まれます。

**Python**

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

client = OpenAI(
    api_key=os.environ["BETTERTOKEN_API_KEY"],
    base_url="https://bettertoken.ai/v1",
    timeout=120.0,
    max_retries=0,
)
response = client.chat.completions.create(
    model=os.environ["BETTERTOKEN_MODEL_ID"],
    messages=[{"role": "user", "content": "Reply with one word: OK"}],
)
print(response.choices[0].message.content)
```

**JavaScript**

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

const client = new OpenAI({
  apiKey: process.env.BETTERTOKEN_API_KEY,
  baseURL: "https://bettertoken.ai/v1",
  timeout: 120000,
  maxRetries: 0,
});
const response = await client.chat.completions.create({
  model: process.env.BETTERTOKEN_MODEL_ID,
  messages: [{ role: "user", content: "Reply with one word: OK" }],
});
console.log(response.choices[0].message.content);
```

**curl**

```bash theme={null}
curl --fail-with-body --max-time 120 "https://bettertoken.ai/v1/chat/completions" \
  -H "Authorization: Bearer $BETTERTOKEN_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"model\":\"$BETTERTOKEN_MODEL_ID\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with one word: OK\"}]}"
```

## Responses を呼び出す

プロンプトには `input` を使います。OpenAI SDK では、テキストを取り出すための便利なプロパティ `output_text` を利用できます。HTTP の JSON 応答には `output` 配列が含まれます。すべての出力項目をテキストとみなさず、メッセージ項目とそのテキスト内容を確認してください。

**Python**

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

client = OpenAI(
    api_key=os.environ["BETTERTOKEN_API_KEY"],
    base_url="https://bettertoken.ai/v1",
    timeout=120.0,
    max_retries=0,
)
response = client.responses.create(
    model=os.environ["BETTERTOKEN_MODEL_ID"],
    input="Reply with one word: OK",
)
print(response.output_text)
```

**JavaScript**

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

const client = new OpenAI({
  apiKey: process.env.BETTERTOKEN_API_KEY,
  baseURL: "https://bettertoken.ai/v1",
  timeout: 120000,
  maxRetries: 0,
});
const response = await client.responses.create({
  model: process.env.BETTERTOKEN_MODEL_ID,
  input: "Reply with one word: OK",
});
console.log(response.output_text);
```

**curl**

```bash theme={null}
curl --fail-with-body --max-time 120 "https://bettertoken.ai/v1/responses" \
  -H "Authorization: Bearer $BETTERTOKEN_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"model\":\"$BETTERTOKEN_MODEL_ID\",\"input\":\"Reply with one word: OK\"}"
```

## Messages を呼び出す

`messages` を使い、`max_tokens` を指定します。この短いテキストリクエストの正常な応答には、`content[0].text` などのテキストブロックが含まれます。通常は `content` を順に処理し、`type: "text"` のブロックだけを読み取ります。

**Python**

```python theme={null}
import os
from anthropic import Anthropic

client = Anthropic(
    api_key=os.environ["BETTERTOKEN_API_KEY"],
    base_url="https://bettertoken.ai",
    timeout=120.0,
    max_retries=0,
)
response = client.messages.create(
    model=os.environ["BETTERTOKEN_MODEL_ID"],
    max_tokens=256,
    messages=[{"role": "user", "content": "Reply with one word: OK"}],
)
for block in response.content:
    if block.type == "text":
        print(block.text)
```

**JavaScript**

```javascript theme={null}
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: process.env.BETTERTOKEN_API_KEY,
  baseURL: "https://bettertoken.ai",
  timeout: 120000,
  maxRetries: 0,
});
const response = await client.messages.create({
  model: process.env.BETTERTOKEN_MODEL_ID,
  max_tokens: 256,
  messages: [{ role: "user", content: "Reply with one word: OK" }],
});
for (const block of response.content) {
  if (block.type === "text") console.log(block.text);
}
```

**curl**

```bash theme={null}
curl --fail-with-body --max-time 120 "https://bettertoken.ai/v1/messages" \
  -H "x-api-key: $BETTERTOKEN_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d "{\"model\":\"$BETTERTOKEN_MODEL_ID\",\"max_tokens\":256,\"messages\":[{\"role\":\"user\",\"content\":\"Reply with one word: OK\"}]}"
```

## 利用可能なモデルを一覧表示する

`Authorization: Bearer` または `x-api-key` 認証を使い、`GET https://bettertoken.ai/v1/models` を送信します。成功時は HTTP `200` が返り、応答の最上位に `data`、`object`、`success` フィールドが含まれます。`data` の各項目には `id`、`object`、`created`、`owned_by`、`supported_endpoint_types` が含まれます。

**curl**

```bash theme={null}
curl --fail-with-body --max-time 120 "https://bettertoken.ai/v1/models" \
  -H "Authorization: Bearer $BETTERTOKEN_API_KEY"
```

`x-api-key` を使う場合は、認証ヘッダーを `-H "x-api-key: $BETTERTOKEN_API_KEY"` に置き換えてください。

**Python**

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

client = OpenAI(
    api_key=os.environ["BETTERTOKEN_API_KEY"],
    base_url="https://bettertoken.ai/v1",
    timeout=120.0,
    max_retries=0,
)
for model in client.models.list():
    print(model.id)
```

返された `id` をリクエストの `model` に指定します。`type` や `display_name` はすべての項目に含まれるわけではないため、必須項目として扱わないでください。モデルの選択には `id` を使い、現在の価格と詳しいモデル説明は[モデル広場](https://bettertoken.ai/pricing)で確認してください。

## よくあるエラー

| 症状 | 確認と対処 |
| - | - |
| URL の誤り、または `404` | OpenAI SDK の Base URL には `/v1` を含めます。Anthropic SDK には含めません。SDK の Base URL に最終的なルートを追加しないでください。 |
| `401`、または認証情報がない | 例では `BETTERTOKEN_API_KEY` から Key を明示的に渡します。OpenAI への直接リクエストは Bearer、Messages への直接リクエストは `x-api-key` を使います。 |
| モデルが見つからない | `YOUR_MODEL_ID` を、モデル広場にある利用可能なモデルの正確な Model ID に置き換えます。選んだエンドポイントで利用できるか確認してください。 |
| 古いエンドポイントにリクエストが届く | SDK の引数と継承された変数を確認します。[競合する環境変数の削除](/ja/best-practices.md#clear-conflicting-environment-variables)を参照してください。 |
| テキストが空、または回答が不完全 | 応答全体と停止理由を確認し、[出力トークン上限](/ja/faq/model-calling/max-tokens.md)を調べてください。 |

### 両方の SDK で同じ Key を使えますか？

はい。一つの BetterToken API Key ですべての利用可能なモデルを使えます。各 SDK に合った Base URL とリクエスト形式を指定してください。

### ストリーミング、ツール、構造化出力も使えますか？

ストリーミングとツール呼び出しへの対応はモデルによって異なります。まず使用する Model ID で小さなリクエストを試し、[ストリーミングとツール呼び出し](/ja/guides/streaming-and-tool-calling.md)に従ってください。JSON の検証やモデルごとの構造化出力については、[構造化 JSON の FAQ](/ja/faq/model-calling/structured-json-pydantic.md)を参照してください。

## 関連ガイド

* [API リファレンスの概要](/ja/api-reference/introduction.md)
* [対応ツール](/ja/ai-tools/overview.md)
* [エラー、ステータスコード、レート制限](/ja/api-reference/errors.md)
* [API Key の保護とタイムアウト](/ja/best-practices.md)
* [キャッシュの課金ルール](/ja/faq/service-assurance/cache-billing.md)

## 公式リファレンス

* [OpenAI Python SDK の公式リポジトリ](https://github.com/openai/openai-python)
* [OpenAI JavaScript SDK の公式リポジトリ](https://github.com/openai/openai-node)
* [Anthropic Python SDK の公式リポジトリ](https://github.com/anthropics/anthropic-sdk-python)
* [Anthropic JavaScript SDK の公式リポジトリ](https://github.com/anthropics/anthropic-sdk-typescript)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.