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

OpenAPI 规范

完整的 ARouter API 使用 OpenAPI 规范进行了文档化: ARouter 目前发布 YAML 规范。您可以使用 Swagger UIPostman 等工具来浏览 API 或生成客户端库。

Base URL

https://api.arouter.ai

认证

所有端点(/healthz 除外)都需要通过以下方式之一进行认证:
方式Header / 参数使用场景
Bearer TokenAuthorization: Bearer <key>OpenAI SDK、大多数客户端
API Key HeaderX-Api-Key: <key>Anthropic SDK
查询参数?key=<key>Gemini SDK
详情请参阅认证指南

请求

请求格式

以下是以 TypeScript 类型表示的请求模式。这将是您向 /v1/chat/completions 端点发起 POST 请求时的请求体。 完整参数列表请参阅参数参考文档。
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 为标准。如果您想发送提供商的原生请求体,请使用该提供商的原生端点或提供商代理

消息类型

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;
    };

工具类型

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
type ResponseFormat =
  | { type: 'json_object' }
  | {
      type: 'json_schema';
      json_schema: {
        name: string;
        strict?: boolean;
        schema: object; // JSON Schema object
      };
    };
详细用法和示例请参阅结构化输出 使用 JSON 模式时,您仍应在系统或用户消息中指示模型以 JSON 格式响应。

可选请求 Header

ARouter 支持以下可选 header 来标识您的应用程序:
  • HTTP-Referer:您的应用 URL,用于在控制台中进行来源追踪
  • X-Title:您的应用显示名称,用于 ARouter 分析
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!' }],
  }),
});
详情请参阅请求归因

模型路由

使用 provider/model 格式指定模型。ARouter 解析提供商前缀并路由到正确的上游。 如果省略 model 参数,将使用租户配置的默认模型。完整路由逻辑请参阅模型路由指南,包括使用 models[]route 的有序候选模型列表。

流式传输

设置 stream: true 可通过 Server-Sent Events 逐 Token 接收响应。SSE 流除 data: 载荷外还可包含注释行,客户端应忽略这些注释。SSE 格式、使用量块、取消和错误处理请参阅流式传输指南。

非标准参数

如果所选模型不支持某个请求参数(例如非 OpenAI 模型中的 logit_bias,或 OpenAI 的 top_k),该参数将被静默忽略。其余参数将转发给上游模型 API。

助手预填充

ARouter 支持让模型补全部分响应。在 messages 数组末尾添加一条 role: "assistant" 的消息:
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 属性。
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 类型

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>;
};

用量

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
  };
};

响应示例

{
  "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 获取。

端点组

OpenAI 兼容

/v1/chat/completions, /v1/embeddings, /v1/models可与任何 OpenAI 兼容 SDK 配合使用。支持 provider/model 路由。

Anthropic 原生

/v1/messages, /v1/messages/batches, /v1/messages/count_tokens与 Anthropic SDK 直接兼容。

Gemini 原生

/v1beta/models/{model}:generateContent与 Google Gemini SDK 直接兼容。

API Key 管理

/api/v1/keys创建、列出、更新和删除 API key。

账单

/api/v1/balance, /api/v1/transactions查询账户余额和交易历史。

提供商代理

/{provider}/{path}将请求直接代理到任何受支持的提供商。

速率限制

速率限制按 API key 应用。默认限制可通过控制台或管理 API 按 key 自定义。
Header描述
X-RateLimit-Limit每个窗口期的最大请求数
X-RateLimit-Remaining剩余请求数
X-RateLimit-Reset窗口期重置时间(Unix 时间戳)

错误响应

所有错误均遵循统一的 JSON 格式:
{
  "error": {
    "message": "description of what went wrong",
    "type": "error_type"
  }
}
完整的错误代码和重试策略请参阅错误处理指南。