> ## 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 的完整参考文档。所有提供商的请求和响应模式均已统一规范，您只需学习一套接口。

ARouter 的请求和响应模式与 OpenAI Chat API 非常相似，有少量差异。ARouter 对所有模型和提供商的模式进行了统一规范，您只需学习一套即可。

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

详情请参阅[认证指南](/zh/authentication)。

## 请求

### 请求格式

以下是以 TypeScript 类型表示的请求模式。这将是您向 `/v1/chat/completions` 端点发起 `POST` 请求时的请求体。

完整参数列表请参阅[参数](/zh/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` 为标准。如果您想发送提供商的原生请求体，请使用该提供商的原生端点或[提供商代理](/zh/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 支持两种模式：

* `{ 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
      };
    };
```

详细用法和示例请参阅[结构化输出](/zh/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!' }],
  }),
});
```

详情请参阅[请求归因](/zh/guides/request-attribution)。

### 模型路由

使用 `provider/model` 格式指定模型。ARouter 解析提供商前缀并路由到正确的上游。

如果省略 `model` 参数，将使用租户配置的默认模型。完整路由逻辑请参阅[模型路由](/zh/model-routing)指南，包括使用 `models[]` 和 `route` 的有序候选模型列表。

### 流式传输

设置 `stream: true` 可通过 Server-Sent Events 逐 Token 接收响应。SSE 流除 `data:` 载荷外还可包含注释行，客户端应忽略这些注释。SSE 格式、使用量块、取消和错误处理请参阅[流式传输](/zh/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="/zh/api-reference/openai/create-chat-completion">
    `/v1/chat/completions`, `/v1/embeddings`, `/v1/models`

    可与任何 OpenAI 兼容 SDK 配合使用。支持 `provider/model` 路由。
  </Card>

  <Card title="Anthropic 原生" icon="brain" href="/zh/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="/zh/api-reference/gemini/generate-content">
    `/v1beta/models/{model}:generateContent`

    与 Google Gemini SDK 直接兼容。
  </Card>

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

    创建、列出、更新和删除 API key。
  </Card>

  <Card title="账单" icon="credit-card" href="/zh/api-reference/billing/get-balance">
    `/api/v1/balance`, `/api/v1/transactions`

    查询账户余额和交易历史。
  </Card>

  <Card title="提供商代理" icon="arrow-right-arrow-left" href="/zh/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"
  }
}
```

完整的错误代码和重试策略请参阅[错误处理](/zh/guides/error-handling)指南。
