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

# API Reference

> ARouter API の完全なリファレンス。すべてのプロバイダーのリクエストとレスポンスのスキーマが統一されているため、1つのインターフェースだけ学べば十分です。

ARouter のリクエストおよびレスポンススキーマは OpenAI Chat API と非常に似ており、わずかな違いがあります。ARouter はすべてのモデルおよびプロバイダーにわたってスキーマを統一しているため、1つだけ学べば十分です。

## OpenAPI 仕様

完全な ARouter API は OpenAPI 仕様を使用してドキュメント化されています：

* YAML：[https://api.arouter.ai/api-reference/openapi.yaml](/api-reference/openapi.yaml)

ARouter は現在 YAML 仕様を公開しています。[Swagger UI](https://swagger.io/tools/swagger-ui/) や [Postman](https://www.postman.com/) などのツールを使用して API を探索したり、クライアントライブラリを生成したりできます。

## Base URL

```
https://api.arouter.ai
```

## 認証

すべてのエンドポイント（`/healthz` を除く）は、以下のいずれかの方法で認証が必要です：

| 方法             | Header / パラメータ                | 使用場面                   |
| -------------- | ----------------------------- | ---------------------- |
| Bearer Token   | `Authorization: Bearer <key>` | OpenAI SDK、ほとんどのクライアント |
| API Key Header | `X-Api-Key: <key>`            | Anthropic SDK          |
| クエリパラメータ       | `?key=<key>`                  | Gemini SDK             |

詳細は[認証ガイド](/jp/authentication)を参照してください。

## リクエスト

### リクエスト形式

以下は TypeScript 型で表現したリクエストスキーマです。これは `/v1/chat/completions` エンドポイントへの `POST` リクエストのボディになります。

完全なパラメータリストは[パラメータ](/jp/api-reference/parameters)リファレンスを参照してください。

```typescript theme={null}
type Request = {
  // ARouter standardizes chat requests on "messages"
  messages?: Message[];

  // If "model" is unspecified, defaults to the tenant's configured default
  model?: string; // e.g. "openai/gpt-5.4" or "anthropic/claude-sonnet-4.6"

  // Force the model to produce specific output format.
  // See "Structured Outputs" guide for supported models.
  response_format?: ResponseFormat;

  stop?: string | string[];
  stream?: boolean; // Enable streaming

  // See Parameters reference
  max_tokens?: number; // Range: [1, context_length)
  temperature?: number; // Range: [0, 2]

  // Tool calling
  // Passed through to providers implementing OpenAI's interface.
  // For providers with custom interfaces, transformed accordingly.
  tools?: Tool[];
  tool_choice?: ToolChoice;
  parallel_tool_calls?: boolean; // Default: true

  // Advanced optional parameters
  seed?: number;
  top_p?: number; // Range: (0, 1]
  top_k?: number; // Range: [1, Infinity) — not available for OpenAI models
  frequency_penalty?: number; // Range: [-2, 2]
  presence_penalty?: number; // Range: [-2, 2]
  repetition_penalty?: number; // Range: (0, 2]
  logit_bias?: { [key: number]: number };
  top_logprobs?: number;
  min_p?: number; // Range: [0, 1]
  top_a?: number; // Range: [0, 1]

  // Reduce latency by providing a predicted output
  prediction?: { type: 'content'; content: string };

  // ARouter routing parameters
  models?: string[]; // Ordered candidate model list — see Model Routing guide
  route?: string;    // Routing mode used with models[]

  // A stable identifier for your end-users (for abuse detection)
  user?: string;
};
```

ARouter の OpenAI 互換チャットエンドポイントは `messages` を標準としています。プロバイダーのネイティブリクエストボディを送信したい場合は、そのプロバイダーのネイティブエンドポイントまたは[プロバイダープロキシ](/jp/guides/provider-proxy)を使用してください。

### メッセージタイプ

```typescript theme={null}
type TextContent = {
  type: 'text';
  text: string;
};

type ImageContentPart = {
  type: 'image_url';
  image_url: {
    url: string; // URL or base64 encoded image data
    detail?: string; // Optional, defaults to "auto"
  };
};

type ContentPart = TextContent | ImageContentPart;

type Message =
  | {
      role: 'user' | 'assistant' | 'system';
      // ContentParts are only for the "user" role:
      content: string | ContentPart[];
      // If "name" is included, it will be prepended like this
      // for non-OpenAI models: `{name}: {content}`
      name?: string;
    }
  | {
      role: 'tool';
      content: string;
      tool_call_id: string;
      name?: string;
    };
```

### ツールタイプ

```typescript theme={null}
type FunctionDescription = {
  description?: string;
  name: string;
  parameters: object; // JSON Schema object
};

type Tool = {
  type: 'function';
  function: FunctionDescription;
};

type ToolChoice =
  | 'none'
  | 'auto'
  | 'required'
  | {
      type: 'function';
      function: {
        name: string;
      };
    };
```

### 構造化出力

`response_format` パラメータはモデルに構造化された JSON レスポンスを強制します。ARouter は2つのモードをサポートしています：

* `{ type: 'json_object' }`：基本 JSON モード — モデルが有効な JSON を返します
* `{ type: 'json_schema', json_schema: { ... } }`：厳格スキーマモード — モデルが指定したスキーマに一致する JSON を返します

```typescript theme={null}
type ResponseFormat =
  | { type: 'json_object' }
  | {
      type: 'json_schema';
      json_schema: {
        name: string;
        strict?: boolean;
        schema: object; // JSON Schema object
      };
    };
```

詳細な使用方法と例については[構造化出力](/jp/guides/features/structured-outputs)を参照してください。

JSON モードを使用する場合も、システムまたはユーザーメッセージでモデルに JSON で応答するよう指示してください。

### オプションのリクエスト Header

ARouter はアプリケーションを識別するための以下のオプション header をサポートしています：

* `HTTP-Referer`：アプリの URL、ダッシュボードでのソーストラッキングに使用
* `X-Title`：ARouter アナリティクスで使用されるアプリの表示名

```typescript theme={null}
fetch('https://api.arouter.ai/v1/chat/completions', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer lr_live_xxxx',
    'HTTP-Referer': 'https://myapp.com', // Optional
    'X-Title': 'My AI App',             // Optional
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/gpt-5.4',
    messages: [{ role: 'user', content: 'Hello!' }],
  }),
});
```

詳細は[リクエスト帰属](/jp/guides/request-attribution)を参照してください。

### モデルルーティング

`provider/model` 形式でモデルを指定します。ARouter はプロバイダープレフィックスを解析して正しいアップストリームにルーティングします。

`model` パラメータが省略された場合、テナントに設定されたデフォルトが使用されます。`models[]` と `route` を使用した順序付き候補モデルリストを含む完全なルーティングロジックは[モデルルーティング](/jp/model-routing)ガイドを参照してください。

### ストリーミング

`stream: true` を設定すると、Server-Sent Events を通じてトークンごとにレスポンスを受信できます。SSE ストリームには `data:` ペイロードに加えてコメント行が含まれる場合があり、クライアントはそれらのコメントを無視する必要があります。SSE 形式、使用量チャンク、キャンセル、エラー処理については[ストリーミング](/jp/guides/streaming)ガイドを参照してください。

### 非標準パラメータ

選択したモデルがリクエストパラメータをサポートしていない場合（非 OpenAI モデルの `logit_bias` や OpenAI の `top_k` など）、そのパラメータは静かに無視されます。残りはアップストリームモデル API に転送されます。

### アシスタントプリフィル

ARouter はモデルに部分的なレスポンスを補完させることをサポートしています。`messages` 配列の末尾に `role: "assistant"` のメッセージを含めてください：

```typescript theme={null}
fetch('https://api.arouter.ai/v1/chat/completions', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer lr_live_xxxx',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/gpt-5.4',
    messages: [
      { role: 'user', content: 'What is the meaning of life?' },
      { role: 'assistant', content: "I'm not sure, but my best guess is" },
    ],
  }),
});
```

## レスポンス

### レスポンス形式

ARouter はすべてのモデルおよびプロバイダーにわたってスキーマを統一し、OpenAI Chat API に準拠しています。

`choices` は常に配列です。ストリーミングがリクエストされた場合、各 choice には `delta` プロパティが含まれ、それ以外の場合は `message` プロパティが含まれます。

```typescript theme={null}
type Response = {
  id: string;
  choices: (NonStreamingChoice | StreamingChoice)[];
  created: number; // Unix timestamp
  model: string;   // The model that was actually used (e.g. "openai/gpt-5.4")
  object: 'chat.completion' | 'chat.completion.chunk';
  provider?: string; // The upstream provider that handled the request

  system_fingerprint?: string; // Only present if the provider supports it

  // Usage data is always returned for non-streaming.
  // When streaming, usage is returned exactly once in the final chunk,
  // before the [DONE] message, with an empty choices array.
  usage?: ResponseUsage;
};
```

### Choice タイプ

```typescript theme={null}
type NonStreamingChoice = {
  finish_reason: string | null; // Normalized finish reason
  native_finish_reason: string | null; // Raw finish reason from the provider
  message: {
    content: string | null;
    role: string;
    tool_calls?: ToolCall[];
  };
  error?: ErrorResponse;
};

type StreamingChoice = {
  finish_reason: string | null;
  native_finish_reason: string | null;
  delta: {
    content: string | null;
    role?: string;
    tool_calls?: ToolCall[];
  };
  error?: ErrorResponse;
};

type ToolCall = {
  id: string;
  type: 'function';
  function: {
    name: string;
    arguments: string; // JSON string
  };
};

type ErrorResponse = {
  code: number;
  message: string;
  metadata?: Record<string, unknown>;
};
```

### 使用量

```typescript theme={null}
type ResponseUsage = {
  /** Including images and tools if any */
  prompt_tokens: number;
  /** The tokens generated */
  completion_tokens: number;
  /** Sum of the above two fields */
  total_tokens: number;

  /** Breakdown of prompt tokens */
  prompt_tokens_details?: {
    cached_tokens: number;        // Tokens read from cache (cache hit)
    cache_write_tokens?: number;  // Tokens written to cache
    audio_tokens?: number;        // Tokens used for input audio
  };

  /** Breakdown of completion tokens */
  completion_tokens_details?: {
    reasoning_tokens?: number;              // Tokens generated for reasoning
    accepted_prediction_tokens?: number;    // Accepted predicted output tokens
    rejected_prediction_tokens?: number;    // Rejected predicted output tokens
    audio_tokens?: number;                  // Tokens generated for audio output
    image_tokens?: number;                  // Tokens generated for image output
  };
};
```

### レスポンス例

```json theme={null}
{
  "id": "chatcmpl-xxxxxxxxxxxxxx",
  "choices": [
    {
      "finish_reason": "stop",
      "native_finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "Hello there!"
      }
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 4,
    "total_tokens": 14,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 0
    }
  },
  "model": "openai/gpt-5.4",
  "provider": "openai",
  "object": "chat.completion",
  "created": 1748000000
}
```

### 終了理由

ARouter は各モデルの `finish_reason` を以下のいずれかの値に統一します：

| 値                | 説明                   |
| ---------------- | -------------------- |
| `stop`           | モデルが自然に完了            |
| `length`         | `max_tokens` の制限に達した |
| `tool_calls`     | モデルがツールを呼び出したい       |
| `content_filter` | コンテンツモデレーションが発動      |
| `error`          | 生成中にエラーが発生           |

アップストリームプロバイダーの生の終了理由は `native_finish_reason` で確認できます。

## エンドポイントグループ

<CardGroup cols={2}>
  <Card title="OpenAI 互換" icon="bolt" href="/jp/api-reference/openai/create-chat-completion">
    `/v1/chat/completions`, `/v1/embeddings`, `/v1/models`

    OpenAI 互換 SDK と組み合わせて使用できます。`provider/model` ルーティングをサポート。
  </Card>

  <Card title="Anthropic ネイティブ" icon="brain" href="/jp/api-reference/anthropic/create-message">
    `/v1/messages`, `/v1/messages/batches`, `/v1/messages/count_tokens`

    Anthropic SDK とのドロップイン互換。
  </Card>

  <Card title="Gemini ネイティブ" icon="wand-magic-sparkles" href="/jp/api-reference/gemini/generate-content">
    `/v1beta/models/{model}:generateContent`

    Google Gemini SDK とのドロップイン互換。
  </Card>

  <Card title="API Key 管理" icon="key" href="/jp/api-reference/keys/create-key">
    `/api/v1/keys`

    API key の作成、一覧表示、更新、削除。
  </Card>

  <Card title="課金" icon="credit-card" href="/jp/api-reference/billing/get-balance">
    `/api/v1/balance`, `/api/v1/transactions`

    アカウント残高と取引履歴を照会。
  </Card>

  <Card title="プロバイダープロキシ" icon="arrow-right-arrow-left" href="/jp/api-reference/proxy/proxy-provider-request">
    `/{provider}/{path}`

    サポートされているプロバイダーにリクエストを直接プロキシ。
  </Card>
</CardGroup>

## レート制限

レート制限は API key ごとに適用されます。デフォルト制限はダッシュボードまたは管理 API を使用して key ごとにカスタマイズできます。

| Header                  | 説明                        |
| ----------------------- | ------------------------- |
| `X-RateLimit-Limit`     | ウィンドウあたりの最大リクエスト数         |
| `X-RateLimit-Remaining` | 残りリクエスト数                  |
| `X-RateLimit-Reset`     | ウィンドウリセット時刻（Unix タイムスタンプ） |

## エラーレスポンス

すべてのエラーは一貫した JSON 形式に従います：

```json theme={null}
{
  "error": {
    "message": "description of what went wrong",
    "type": "error_type"
  }
}
```

エラーコードの完全なリストと再試行戦略については[エラーハンドリング](/jp/guides/error-handling)ガイドを参照してください。
