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

# Create Chat Completion

> OpenAI 互換のリクエスト/レスポンスでチャットモデルを呼び出します。

**Endpoint:** `POST /chat/completions`

多くの統合はこのエンドポイントから始めます。`model` と `messages` を送ると、OpenAI 互換の completion が返ります。ビジョン対応モデルでは `messages[].content` に画像入力も渡せます。

## リクエスト例

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": "Reply with exactly: connected"
      }
    ]
  }'
```

## OpenAI SDK

<CodeGroup>
  ```python Python theme={null}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["YOUROUTER_API_KEY"],
      base_url="https://api.yourouter.ai/v1",
  )

  completion = client.chat.completions.create(
      model="gpt-4o",
      messages=[{"role": "user", "content": "Reply with exactly: connected"}],
  )

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

  ```javascript Node.js theme={null}
  import OpenAI from 'openai';

  const openai = new OpenAI({
    apiKey: process.env.YOUROUTER_API_KEY,
    baseURL: 'https://api.yourouter.ai/v1',
  });

  const completion = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [{ role: 'user', content: 'Reply with exactly: connected' }],
  });

  console.log(completion.choices[0].message.content);
  ```
</CodeGroup>

## ヘッダー

| Header          | 必須  | 説明                                                                              |
| --------------- | --- | ------------------------------------------------------------------------------- |
| `Authorization` | はい  | `Bearer <YOUROUTER_API_KEY>`                                                    |
| `Content-Type`  | はい  | `application/json`                                                              |
| `vendor`        | いいえ | 自動ルーティングには `auto` を指定するか省略します。`openai`、`anthropic`、`google` などの値でプロバイダーを固定できます。 |

## ボディパラメータ

<ResponseField name="model" type="string" required>
  呼び出すモデル ID（例: `gpt-4o`, `claude-sonnet-4-20250514`, `gemini-2.5-flash`）。
</ResponseField>

<ResponseField name="messages" type="array" required>
  順序付きの会話メッセージ配列です。各メッセージには `role` と `content` を含めます。
</ResponseField>

<ResponseField name="stream" type="boolean" default="false">
  `true` の場合、Server-Sent Events の増分 chunk としてレスポンスを返します。
</ResponseField>

<ResponseField name="temperature" type="number">
  モデルが対応する場合のサンプリング温度。
</ResponseField>

<ResponseField name="max_tokens" type="integer">
  モデルが対応する場合の出力上限。
</ResponseField>

<ResponseField name="tools" type="array">
  関数呼び出しまたは tool use に対応するモデルへ渡すツール定義です。
</ResponseField>

## マルチモーダル（画像入力）

ビジョン対応モデルでは、`content` をブロック配列として送ります。指示には `text` ブロックを使い、画像には `image_url` ブロックを使います。

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "Describe this image in one sentence."
          },
          {
            "type": "image_url",
            "image_url": {
              "url": "https://example.com/image.jpg"
            }
          }
        ]
      }
    ]
  }'
```

非公開画像は base64 data URL:

```json theme={null}
{
  "type": "image_url",
  "image_url": {
    "url": "data:image/jpeg;base64,<BASE64_IMAGE>"
  }
}
```

### PDF ファイル入力

対象モデルと上流プロバイダーが OpenAI 互換のファイルコンテンツブロックに対応している場合、`messages[].content` に PDF を渡せます。`file_data` には PDF の生バイト列を base64 エンコードした値を入れます。

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "file",
            "file": {
              "filename": "document.pdf",
              "file_data": "<BASE64_PDF>"
            }
          },
          {
            "type": "text",
            "text": "Extract a summary and key conclusions from this PDF."
          }
        ]
      }
    ]
  }'
```

<Note>
  PDF 入力はすべてのモデルで使えるわけではありません。Gemini 原生または Claude 原生の PDF 動作が必要な場合は、[マルチモーダルガイド](/ja/guides/multimodal) の provider-native 例を参照してください。
</Note>

Gemini ネイティブ形式や Claude ネイティブ形式を含む追加例は、[マルチモーダルガイド](/ja/guides/multimodal) を参照してください。

## レスポンス

成功時は OpenAI Chat Completions 形式です。

```json theme={null}
{
  "id": "chatcmpl_example",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "connected"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 1,
    "total_tokens": 13
  }
}
```

生成テキストは通常、次のフィールドに入ります。

```text theme={null}
choices[0].message.content
```

## ルーティング

デフォルトでは自動ルーティングです。

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]}'
```

`vendor` を送るとプロバイダーを固定できます。

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -H "vendor: openai" \
  -d '{"model": "gpt-4o", "messages": [{"role": "user", "content": "Hello"}]}'
```

## ストリーミング

`stream` を `true` にすると、Server-Sent Events の増分 chunk としてレスポンスを受け取れます。

```bash theme={null}
curl https://api.yourouter.ai/v1/chat/completions \
  -H "Authorization: Bearer $YOUROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "stream": true,
    "messages": [
      {
        "role": "user",
        "content": "Explain model routing in two sentences."
      }
    ]
  }'
```

## よくあるエラー

| ステータス | 原因                      | 確認                                   |
| ----- | ----------------------- | ------------------------------------ |
| `400` | リクエストボディが不正、または未対応パラメータ | `model`、`messages`、JSON 形式を確認してください。 |
| `401` | API キーが未指定、または無効        | `Authorization` ヘッダーを確認してください。       |
| `429` | プロバイダーのレート制限、または同時実行制限  | バックオフして再試行するか、自動ルーティングを使用してください。     |
| `500` | ゲートウェイまたは上流プロバイダーのエラー   | 安全に再試行し、サポート用にリクエスト ID を保存してください。    |

モデル ID と固定例は [モデル](/ja/model) と [ルーティング](/ja/guides/router) を参照してください。
