AIClient2API

GitHub

Self-hosted multi-protocol AI API proxy for Antigravity, Codex, Grok, Kiro, OpenAI, Claude, and custom providers. Supports OpenAI-compatible API, Claude API, Gemini protocol conversion, GPT, Grok Build, Claude Opus, Gemini Pro, Kimi, MiniMax, provider pools, smart routing, and automatic failover.

8,585 stars JavaScript #aicoding#free
RAW Doc

Skills/Aiclient Cli Usage

---
name: aiclient-cli-usage
description: Use when an agent needs to understand, configure, or call the AIClient2API service via its CLI tools or REST APIs.
---

AIClient2API CLI & API Usage Skill

Overview


This skill provides instructions for AI agents to interact with the AIClient2API service. It covers how to discover available commands and navigate the exhaustive API surface using both local CLI and remote REST interfaces.

Self-Discovery Modes

CRITICAL: Regardless of how you access the service, using REST APIs (for management or AI tasks) requires the Server Address and appropriate credentials. Always ask the user for the Server Address (use http://localhost:3000 as default for local) and Admin Password before attempting API-based tasks.

1. Local Mode (CLI & REST API)


Use these when you have shell access to the server environment. In this mode, you can use both local CLI tools and REST APIs:
- CLI Help: npm run help (Add --json for structured data)
- CLI API Guide: npm run example:api (Add --json for structured data)
- REST API: You can access all endpoints via http://localhost:<PORT> (Default: 3000).

2. Remote Mode (REST API Only)


Use these when interacting with a running instance over the network without shell access:
- Help JSON: GET <SERVER_ADDR>/api/help (Public, No Auth)
- API Guide JSON: GET <SERVER_ADDR>/api/example (Public, No Auth)
- REST API: Use the user-provided Server Address.

When to Use


- When you need to understand, configure, or call the AIClient2API service.
- To programmatically manage model providers or account pools.
- To monitor system health, logs, or usage.

Core API Categories (AI vs. Management)

0. Public Endpoints (No Auth Required)


Use these for self-discovery or system monitoring:
- GET /api/help: Get full API help documentation (JSON).
- GET /api/example: Get API calling examples (JSON).
- GET /provider_health: Detailed health status of all model providers.
- POST /api/login: Exchange Admin Password for a dynamic Token.

1. AI Business Path (/v1/, /v1beta/, /count_tokens)


- Purpose: AI model inference (chat, image, token counting).
- Auth: Static API Key. Ask the user for this if not provided.
- Header: Authorization: Bearer <YOUR_API_KEY>

2. Management Path (/api/, /health, /provider_health)


- Purpose: Server config, node pool management, logs, stats.
- Auth: Dynamic Token via /api/login. Ask the user for the Server Address and Admin Password.
- Header: Authorization: Bearer <ADMIN_TOKEN> (Except for /api/login and public health checks).

Advanced Patterns

Path Routing


Force a specific provider by prefixing the AI business path:
- /gemini-cli-oauth/v1/chat/completions
- /claude-custom/v1/messages

Real-time Logs (SSE)


Subscribe to GET /api/events via EventSource for live system output.

Quick Reference

| Mode | Method | Command/Endpoint | Format |
|------|--------|------------------|--------|
| Local | CLI | npm run help -- --json | JSON |
| Local | CLI | npm run example:api | Text |
| Local | REST | GET http://localhost:3000/api/help | JSON |
| Remote | REST | GET <SERVER_ADDR>/api/help | JSON |
| Remote | REST | GET <SERVER_ADDR>/api/example?format=text | Text |

Common Mistakes


- Wrong Key: Using the static AI Key for management APIs (causes 401).
- No Login: Attempting to fetch /api/config without first calling /api/login.
- Format Mismatch: Expecting JSON from a CLI command without the --json flag.

Code Example: Management API Flow


javascript
// 1. Login to get token
const login = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ password: 'admin' })
});
const { token } = await login.json();

// 2. Use token for management
const nodes = await fetch('/api/providers', {
headers: { 'Authorization': Bearer ${token} }
});

---

OPENCLAW CONFIG GUIDE

OpenClaw Configuration Guide

Quick configuration guide for using AIClient2API with OpenClaw.

---

Prerequisites

1. Start AIClient2API service
2. Configure at least one provider in Web UI (http://localhost:3000)
3. Note the API Key from configuration file
4. Install OpenClaw
- Docker version: justlikemaki/openclaw-docker-cn-im
- Or use other installation methods

---

Configuration Methods

Use Case: For Gemini models

json5
{
env: {
AICLIENT2API_KEY: "your-api-key"
},
agents: {
defaults: {
model: { primary: "aiclient2api/gemini-3-flash-preview" },
models: {
"aiclient2api/gemini-3-flash-preview": { alias: "Gemini 3 Flash" }
}
}
},
models: {
mode: "merge",
providers: {
aiclient2api: {
baseUrl: "http://localhost:3000/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [
{
id: "gemini-3-flash-preview",
name: "Gemini 3 Flash Preview",
reasoning: false,
input: ["text", "image"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1000000,
maxTokens: 8192
}
]
}
}
}
}

Method 2: Claude Protocol

Use Case: For Claude models with features like Prompt Caching

json5
{
env: {
AICLIENT2API_KEY: "your-api-key"
},
agents: {
defaults: {
model: { primary: "aiclient2api/claude-sonnet-4-5" },
models: {
"aiclient2api/claude-sonnet-4-5": { alias: "Claude Sonnet 4.5" }
}
}
},
models: {
mode: "merge",
providers: {
aiclient2api: {
baseUrl: "http://localhost:3000",
apiKey: "${AICLIENT2API_KEY}",
api: "anthropic-messages",
models: [
{
id: "claude-sonnet-4-5",
name: "Claude Sonnet 4.5",
reasoning: false,
input: ["text", "image"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 200000,
maxTokens: 8192
}
]
}
}
}
}

---

Specify Provider (Optional)

Specify a specific provider via routing parameters:

json5
{
models: {
providers: {
// Kiro Claude (OpenAI Protocol)
"aiclient2api-kiro": {
baseUrl: "http://localhost:3000/claude-kiro-oauth/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [...]
},

// Kiro Claude (Claude Protocol)
"aiclient2api-kiro-claude": {
baseUrl: "http://localhost:3000/claude-kiro-oauth",
apiKey: "${AICLIENT2API_KEY}",
api: "anthropic-messages",
models: [...]
},

// Gemini CLI (OpenAI Protocol)
"aiclient2api-gemini": {
baseUrl: "http://localhost:3000/gemini-cli-oauth/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [...]
},

// Antigravity (OpenAI Protocol)
"aiclient2api-antigravity": {
baseUrl: "http://localhost:3000/gemini-antigravity/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [...]
}
}
}
}

---

Configure Fallback

json5
{
agents: {
defaults: {
model: {
primary: "aiclient2api/claude-sonnet-4-5",
fallbacks: [
"aiclient2api/gemini-3-flash-preview"
]
}
}
}
}

---

Common Commands

bash

List all models


openclaw models list

Switch model


openclaw models set aiclient2api/claude-sonnet-4-5

Chat with specific model


openclaw chat --model aiclient2api/gemini-3-flash-preview "your question"

---

Protocol Comparison

| Feature | OpenAI Protocol | Claude Protocol |
|---------|----------------|-----------------|
| Base URL | http://localhost:3000/v1 | http://localhost:3000 |
| API Type | openai-completions | anthropic-messages |
| Supported Models | All models | Claude only |
| Special Features | - | Prompt Caching, Extended Thinking |

---

FAQ

Q: Connection failed?
- Confirm AIClient2API service is running
- Check if Base URL is correct (OpenAI protocol needs /v1 suffix)
- Try using 127.0.0.1 instead of localhost

Q: 401 error?
- Check if API Key is correctly configured
- Confirm environment variable AICLIENT2API_KEY is set

Q: Model unavailable?
- Confirm provider is configured in AIClient2API Web UI
- Run openclaw gateway restart to restart gateway
- Run openclaw models list to verify model list

---

For more information, see AIClient2API Documentation

---

OPENCLAW CONFIG GUIDE JA

OpenClaw 設定ガイド

OpenClaw で AIClient2API を使用するためのクイック設定ガイド。

---

前提条件

1. AIClient2API サービスを起動
2. Web UI (http://localhost:3000) で少なくとも1つのプロバイダーを設定
3. 設定ファイルから API Key を記録
4. OpenClaw をインストール
- Docker バージョン:justlikemaki/openclaw-docker-cn-im
- または他のインストール方法を使用

---

設定方法

方法1:OpenAI プロトコル(推奨)

使用例:Gemini モデルを使用する場合

json5
{
env: {
AICLIENT2API_KEY: "your-api-key"
},
agents: {
defaults: {
model: { primary: "aiclient2api/gemini-3-flash-preview" },
models: {
"aiclient2api/gemini-3-flash-preview": { alias: "Gemini 3 Flash" }
}
}
},
models: {
mode: "merge",
providers: {
aiclient2api: {
baseUrl: "http://localhost:3000/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [
{
id: "gemini-3-flash-preview",
name: "Gemini 3 Flash Preview",
reasoning: false,
input: ["text", "image"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1000000,
maxTokens: 8192
}
]
}
}
}
}

方法2:Claude プロトコル

使用例:Prompt Caching などの機能を持つ Claude モデルを使用する場合

json5
{
env: {
AICLIENT2API_KEY: "your-api-key"
},
agents: {
defaults: {
model: { primary: "aiclient2api/claude-sonnet-4-5" },
models: {
"aiclient2api/claude-sonnet-4-5": { alias: "Claude Sonnet 4.5" }
}
}
},
models: {
mode: "merge",
providers: {
aiclient2api: {
baseUrl: "http://localhost:3000",
apiKey: "${AICLIENT2API_KEY}",
api: "anthropic-messages",
models: [
{
id: "claude-sonnet-4-5",
name: "Claude Sonnet 4.5",
reasoning: false,
input: ["text", "image"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 200000,
maxTokens: 8192
}
]
}
}
}
}

---

プロバイダーの指定(オプション)

ルーティングパラメータで特定のプロバイダーを指定:

json5
{
models: {
providers: {
// Kiro Claude(OpenAI プロトコル)
"aiclient2api-kiro": {
baseUrl: "http://localhost:3000/claude-kiro-oauth/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [...]
},

// Kiro Claude(Claude プロトコル)
"aiclient2api-kiro-claude": {
baseUrl: "http://localhost:3000/claude-kiro-oauth",
apiKey: "${AICLIENT2API_KEY}",
api: "anthropic-messages",
models: [...]
},

// Gemini CLI(OpenAI プロトコル)
"aiclient2api-gemini": {
baseUrl: "http://localhost:3000/gemini-cli-oauth/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [...]
},

// Antigravity(OpenAI プロトコル)
"aiclient2api-antigravity": {
baseUrl: "http://localhost:3000/gemini-antigravity/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [...]
}
}
}
}

---

フォールバックの設定

json5
{
agents: {
defaults: {
model: {
primary: "aiclient2api/claude-sonnet-4-5",
fallbacks: [
"aiclient2api/gemini-3-flash-preview"
]
}
}
}
}

---

よく使うコマンド

bash

すべてのモデルをリスト表示


openclaw models list

モデルを切り替え


openclaw models set aiclient2api/claude-sonnet-4-5

特定のモデルでチャット


openclaw chat --model aiclient2api/gemini-3-flash-preview "あなたの質問"

---

プロトコル比較

| 機能 | OpenAI プロトコル | Claude プロトコル |
|------|------------------|------------------|
| Base URL | http://localhost:3000/v1 | http://localhost:3000 |
| API タイプ | openai-completions | anthropic-messages |
| サポートモデル | すべてのモデル | Claude のみ |
| 特殊機能 | - | Prompt Caching、Extended Thinking |

---

よくある質問

Q: 接続に失敗しますか?
- AIClient2API サービスが実行中であることを確認
- Base URL が正しいか確認(OpenAI プロトコルには /v1 サフィックスが必要)
- localhost の代わりに 127.0.0.1 を使用してみる

Q: 401 エラー?
- API Key が正しく設定されているか確認
- 環境変数 AICLIENT2API_KEY が設定されているか確認

Q: モデルが利用できない?
- AIClient2API Web UI でプロバイダーが設定されているか確認
- openclaw gateway restart を実行してゲートウェイを再起動
- openclaw models list を実行してモデルリストを確認

---

詳細については、AIClient2API ドキュメント を参照してください

---

OPENCLAW CONFIG GUIDE ZH

OpenClaw 配置指南

在 OpenClaw 中使用 AIClient2API 的快速配置指南。

---

前置准备

1. 启动 AIClient2API 服务
2. 在 Web UI (http://localhost:3000) 配置至少一个提供商
3. 记录配置文件中的 API Key
4. 安装 OpenClaw
- Docker 版本:justlikemaki/openclaw-docker-cn-im
- 或使用其他安装方式

---

配置方式

方式一:OpenAI 协议(推荐)

适用场景:使用 Gemini 模型

json5
{
env: {
AICLIENT2API_KEY: "your-api-key"
},
agents: {
defaults: {
model: { primary: "aiclient2api/gemini-3-flash-preview" },
models: {
"aiclient2api/gemini-3-flash-preview": { alias: "Gemini 3 Flash" }
}
}
},
models: {
mode: "merge",
providers: {
aiclient2api: {
baseUrl: "http://localhost:3000/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [
{
id: "gemini-3-flash-preview",
name: "Gemini 3 Flash Preview",
reasoning: false,
input: ["text", "image"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1000000,
maxTokens: 8192
}
]
}
}
}
}

方式二:Claude 协议

适用场景:使用 Claude 模型,需要 Prompt Caching 等特性

json5
{
env: {
AICLIENT2API_KEY: "your-api-key"
},
agents: {
defaults: {
model: { primary: "aiclient2api/claude-sonnet-4-5" },
models: {
"aiclient2api/claude-sonnet-4-5": { alias: "Claude Sonnet 4.5" }
}
}
},
models: {
mode: "merge",
providers: {
aiclient2api: {
baseUrl: "http://localhost:3000",
apiKey: "${AICLIENT2API_KEY}",
api: "anthropic-messages",
models: [
{
id: "claude-sonnet-4-5",
name: "Claude Sonnet 4.5",
reasoning: false,
input: ["text", "image"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 200000,
maxTokens: 8192
}
]
}
}
}
}

---

指定提供商(可选)

通过路由参数指定特定提供商:

json5
{
models: {
providers: {
// Kiro 提供的 Claude (OpenAI 协议)
"aiclient2api-kiro": {
baseUrl: "http://localhost:3000/claude-kiro-oauth/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [...]
},

// Kiro 提供的 Claude (Claude 协议)
"aiclient2api-kiro-claude": {
baseUrl: "http://localhost:3000/claude-kiro-oauth",
apiKey: "${AICLIENT2API_KEY}",
api: "anthropic-messages",
models: [...]
},

// Gemini CLI (OpenAI 协议)
"aiclient2api-gemini": {
baseUrl: "http://localhost:3000/gemini-cli-oauth/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [...]
},

// Antigravity (OpenAI 协议)
"aiclient2api-antigravity": {
baseUrl: "http://localhost:3000/gemini-antigravity/v1",
apiKey: "${AICLIENT2API_KEY}",
api: "openai-completions",
models: [...]
}
}
}
}

---

配置 Fallback

json5
{
agents: {
defaults: {
model: {
primary: "aiclient2api/claude-sonnet-4-5",
fallbacks: [
"aiclient2api/gemini-3-flash-preview"
]
}
}
}
}

---

常用命令

bash

列出所有模型


openclaw models list

切换模型


openclaw models set aiclient2api/claude-sonnet-4-5

使用指定模型对话


openclaw chat --model aiclient2api/gemini-3-flash-preview "你的问题"

---

协议对比

| 特性 | OpenAI 协议 | Claude 协议 |
|------|------------|------------|
| Base URL | http://localhost:3000/v1 | http://localhost:3000 |
| API 类型 | openai-completions | anthropic-messages |
| 支持模型 | 所有模型 | 仅 Claude |
| 特殊特性 | - | Prompt Caching、Extended Thinking |

---

常见问题

Q: 连接失败?
- 确认 AIClient2API 服务运行中
- 检查 Base URL 是否正确(OpenAI 协议需要 /v1 后缀)
- 尝试使用 127.0.0.1 替代 localhost

Q: 401 错误?
- 检查 API Key 是否正确配置
- 确认环境变量 AICLIENT2API_KEY 已设置

Q: 模型不可用?
- 在 AIClient2API Web UI 确认已配置对应提供商
- 运行 openclaw gateway restart 重启网关
- 运行 openclaw models list 验证模型列表

---

更多信息请参考 AIClient2API 文档

---

OPENCODE CONFIG EXAMPLE

OpenCode 配置示例及重点解释

本文档提供了一个典型的 opencode 配置文件示例,并对其中的关键配置项进行了详细解释,帮助您快速理解如何配置不同的 AI 服务提供商。

配置示例 (config.json)

text
/ Detailed source-code truncated for AI context efficiency. /

配置重点解释

1. provider (服务提供商配置)


这是配置的核心部分,每个键(如 kiro, gemini-cli)代表一个独立的服务提供商实例。

* npm (SDK 适配器):
* 指定底层使用的 AI SDK。例如:
* @ai-sdk/anthropic: 用于 Anthropic (Claude) 系列模型。
* @ai-sdk/openai-compatible: 用于兼容 OpenAI 接口标准的模型。
* @ai-sdk/google: 用于 Google Gemini 系列模型。
* 重点: 必须确保 npm 字段与您要使用的模型协议匹配,否则会导致连接失败。

* options (连接参数):
* baseURL: API 的访问地址。在示例中,许多是内网或中转地址(如 http://localhost:3000/...)。
* apiKey: 访问 API 所需的身份验证密钥。

* models (模型映射):
* 定义该提供商下可用的模型列表。
* 键名 (ID): 实际调用时使用的模型 ID(例如 claude-opus-4-5)。
* name: 在 UI 界面上显示的友好名称。
* 重点: 这里的键名必须与服务端实际支持的模型标识符一致。

2. 区分同类型的不同实例


在示例中,有两个 gemini 相关的配置:gemini-antigravitygemini-cli
* 它们虽然都使用 @ai-sdk/google,但通过不同的 baseURL 区分。
* 这允许您在同一配置中接入来自不同网关或环境的同类模型,并通过自定义的 name(如 gemini-2.5-flash-antigravity vs gemini-2.5-flash-geminicli)在前端进行区分。

3. $schema


* 用于提供 JSON 模式验证。在支持的编辑器(如 VS Code)中,它可以为您提供自动补全和实时错误检查。

---

PROVIDER ADAPTER GUIDE

AIClient2API Provider 接入指南

本文档详细说明了如何向 AIClient2API 项目接入全新的模型提供商(Provider),涵盖从后端核心逻辑到前端 UI 管理的全流程调整。

1. 接入流程概览

1. 后端常量定义:在 src/utils/common.js 中添加标识。
2. 核心 Service 开发:在 src/providers/ 实现 API 请求逻辑。
3. 适配器注册:在 src/providers/adapter.js 注册并实现适配器类。
4. 模型与号池配置:在 src/providers/provider-models.jssrc/providers/provider-pool-manager.js 配置。
5. 前端 UI 全方位调整
* static/app/provider-manager.js:号池显示与顺序。
* static/app/file-upload.js:上传路径映射。
* static/app/modal.js:配置字段显示顺序。
* static/app/utils.js:定义配置字段元数据。
* static/components/section-config.html:配置按钮。
* static/components/section-guide.html:使用指南。
* static/app/routing-examples.js:路由调用示例。
6. 系统级映射(必做):在 OAuth 处理器、凭据关联工具、用量统计等模块中建立映射。

---

2. 后端核心实现

2.1 定义常量


修改 src/utils/common.js,在 MODEL_PROVIDER 中添加新 key(格式建议:协议-名称-类型)。

2.2 核心 Service (Core)


src/providers/ 下创建新目录并实现 NewProviderApiService 类。
必选方法constructor(config), initialize(), listModels(), generateContent(), generateContentStream()
可选功能:若支持用量查询,需实现 getUsageLimits();若支持 Token 统计,需实现 countTokens()

2.3 注册适配器


src/providers/adapter.js 中:
1. 继承 ApiServiceAdapter 实现特定提供商的适配器类。
2. 适配器类需按需重写 generateContent, generateContentStream, listModels, getUsageLimits, countTokens, refreshToken 等方法,并转发给核心 Service。
3. 在 getServiceAdapter 工厂方法中添加对应的 switch 分支,根据 MODEL_PROVIDER 返回实例。

2.4 模型与号池默认配置


* 模型列表:在 src/providers/provider-models.jsPROVIDER_MODELS 对象中添加默认支持的模型 ID。
* 健康检查默认值:在 src/providers/provider-pool-manager.js 的以下位置配置:
* DEFAULT_HEALTH_CHECK_MODELS:指定用于健康检查的默认模型。
* checkAndRefreshExpiringNodes:指定凭据文件路径键名。
* _buildHealthCheckRequests:若有特殊请求格式需求,需在此添加逻辑。

---

3. 前端界面调整

3.1 字段定义与元数据 (static/app/utils.js)


getProviderTypeFields 函数中定义该提供商所需的配置字段(如 API Key, Base URL, 凭据路径等),指定字段类型和占位符。

3.2 字段显示顺序 (static/app/modal.js)


getFieldOrder 函数的 fieldOrderMap 中添加新提供商的字段显示顺序。

3.3 号池显示逻辑 (static/app/provider-manager.js)


* 显示顺序:将新标识和显示名称添加到 providerConfigs 数组。
* 授权按钮:若支持 OAuth,在 generateAuthButtonoauthProviders 数组中添加标识。
* 认证逻辑:若支持 OAuth 或批量导入,需在 handleGenerateAuthUrl 中实现相应的触发逻辑(如弹出认证方式选择器)。

3.4 凭据上传路由 (static/app/file-upload.js)


* 修改 getProviderKey,建立提供商标识与 configs/ 子目录名的映射(例如:new-provider-api -> new-provider)。

3.5 凭据文件管理筛选器


需要在以下三个位置添加新提供商的筛选支持:

#### 3.5.1 HTML 筛选器选项 (static/components/section-upload-config.html)
id="configProviderFilter"<select> 元素中添加新的 <option>

html
<option value="new-provider-type" data-i18n="upload.providerFilter.newProvider">New Provider OAuth</option>

#### 3.5.2 JavaScript 提供商映射 (static/app/upload-config-manager.js)
detectProviderFromPath() 函数的 providerMappings 数组中添加映射关系:

javascript
{
patterns: ['configs/new-provider/', '/new-provider/'],
providerType: 'new-provider-type',
displayName: 'New Provider OAuth',
shortName: 'new-provider-oauth'
}

#### 3.5.3 多语言文案 (static/app/i18n.js)
在中文和英文的翻译对象中添加筛选器、配置项、认证步骤等相关文案:

javascript
// 中文版本 (zh-CN)
'upload.providerFilter.newProvider': 'New Provider OAuth',
'config.newProvider.apiKey': 'API 密钥',

// 英文版本 (en-US)
'upload.providerFilter.newProvider': 'New Provider OAuth',
'config.newProvider.apiKey': 'API Key',

3.6 配置管理界面 (static/components/section-config.html)


* 必须添加:在 id="modelProvider"(初始化提供商选择)容器中添加对应的 provider-tag 按钮。
* 可选添加:在 id="proxyProviders"(代理开关)中同步添加。

3.7 路由调用示例 (static/app/routing-examples.js)


routingConfigs 数组中添加该提供商的路径定义,并在 generateCurlExample 中处理协议转换逻辑说明。

3.8 指南与教程 (static/components/section-guide.html)


* 在"支持的模型提供商"中添加新提供商的介绍和支持情况(Badge)。
* 在"客户端配置指南"中补充该提供商的调用路径提示。

---

4. 全局系统映射 (关键)

为确保新提供商的功能完整(如多账号自动切换、用量监控),必须在以下位置建立映射:

4.1 凭据路径键名映射 (src/services/service-manager.js)


getServiceAdapter 逻辑相关的 credPathKey 映射中,指定该提供商对应的配置文件路径键名。

4.2 自动关联工具 (src/utils/provider-utils.js)


CONFIG_FILE_PATTERNS 数组中添加配置,以便系统能根据文件路径自动识别并关联凭据:
javascript
{
patterns: ['configs/new-dir/', '/new-dir/'],
providerType: 'new-provider-api',
credPathKey: 'NEW_PROVIDER_CREDS_FILE_PATH'
}

4.3 用量统计映射 (src/ui-modules/usage-api.js)


* 将标识添加到 supportedProviders 数组。
* 在 credPathKey 映射中添加路径键名,以便前端能展示每个账号的配额/用量。
* 在 getAdapterUsage 中根据需要处理原始数据的格式化。

4.4 OAuth 处理器


* 处理器逻辑:在 src/auth/oauth-handlers.js 中导出处理函数。
* 路由分发:在 src/ui-modules/oauth-api.jshandleGenerateAuthUrl 中分发到相应的处理器。
* 回调处理:若涉及 HTTP 回调,需在 src/auth/ 下实现回调服务器逻辑。

---

5. 注意事项


1. 协议对齐:本项目内部默认使用 Gemini 协议。若上游为 OpenAI 协议,需在 src/convert/ 实现转换,或在 Core Service 中自行处理。
2. 安全性:不要在 Core 代码中硬编码 Key,始终从 config 中读取动态注入的凭据。
3. 异常捕获:Core 代码必须抛出标准错误(包含 status),以便号池管理器识别并自动隔离失效账号。401/403 错误通常触发 UUID 刷新或凭据切换。
4. 异步刷新:利用 V2 架构的读写分离,耗时的认证逻辑应放入 refreshToken 并在后台异步执行。

---

README

<div align="center">

<img src="src/img/logo-mid.webp" alt="logo" style="width: 128px; height: 128px;margin-bottom: 3px;">

AIClient2API(A2)🚀

A powerful proxy that can unify the requests of various client-only large model APIs (Gemini CLI, Antigravity, Codex, Grok, Kiro ...), simulate requests, and encapsulate them into a local OpenAI-compatible interface.

</div>

<div align="center">

<table align="center">
<thead>
<tr>
<th align="center">Docker Downloads > 100k</th>
<th align="center">Ranked #2 on Trendshift</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center" valign="middle">
<img src="https://docker-card.justlikemaki.workers.dev/justlikemaki/aiclient-2-api?layout=compact&theme=github" alt="AIClient2API" style="width: 100%; max-width: 520px; height: 320px;object-fit: contain;" />
</td>
<td align="center" valign="middle">
<a href="https://trendshift.io/repositories/15832" target="_blank"><img src="https://trendshift.io/api/badge/repositories/15832" alt="justlovemaki%2FAIClient-2-API | Trendshift" style="width: 360px; height: 120px;"/></a>
</td>
</tr>
</tbody>
</table>

[](https://deepwiki.com/justlovemaki/AIClient-2-API)
[](https://www.gnu.org/licenses/gpl-3.0)
[](https://nodejs.org/)
[](https://hub.docker.com/r/justlikemaki/aiclient-2-api)
[](https://github.com/justlovemaki/AIClient-2-API/stargazers)
[](https://github.com/justlovemaki/AIClient-2-API/issues)

🔧 OpenClaw Config | 中文 | 👉 English | 日本語 | 📚 Documentation

</div>

---


💎 Sponsors

Sponsors are listed in chronological order; all are recommended for registration and use.

<table width="100%">
<tr>
<td width="25%" align="center" valign="middle">
<a href="https://www.packyapi.com/register?aff=AIClient2API">
<img src="static/packycode.png" alt="PackyCode Sponsor" width="180">
</a>
</td>
<td width="75%" align="left" valign="middle">
PackyCode is a reliable and efficient API relay service provider, offering relay services for Claude Code, Codex, Gemini, and more. PackyCode provides special discounts for our software users: <a href="https://www.packyapi.com/register?aff=AIClient2API">register using this link</a> and enter the <strong>AIClient2API</strong> promo code during recharge to get <strong>10% off</strong>.
</td>
</tr>
<tr>
<td width="25%" align="center" valign="middle">
<a href="https://apikey.fun/register?aff=AIClient2API">
<img src="static/apikey.fun.png" alt="APIKEY.FUN Sponsor" width="180">
</a>
</td>
<td width="75%" align="left" valign="middle">
Thanks to APIKEY.FUN for sponsoring this project! APIKEY.FUN is a professional enterprise-grade AI relay station, dedicated to providing stable, efficient, and low-cost AI model API access services for enterprises and individual developers. The platform supports mainstream popular models such as Claude, OpenAI, and Gemini, with prices as low as 7% of the official original price. Register through the <a href="https://apikey.fun/register?aff=AIClient2API">project's exclusive link</a> to enjoy an exclusive discount of up to <strong>5% off (95% of original price)</strong> for permanent recharges.
</td>
</tr>

<tr>
<td width="25%" align="center" valign="middle">
<a href="https://www.atlascloud.ai/console/coding-plan">
<img src="static/atlascloud.png" alt="Atlas Cloud Sponsor" width="180">
</a>
</td>
<td width="75%" align="left" valign="middle">
Thanks to Atlas Cloud for sponsoring this project! Atlas Cloud is a <strong>full-modal AI inference platform</strong> that gives developers a single AI API to access video generation, image generation, and LLM APIs. Instead of managing multiple vendor integrations, you connect once and get unified access to <strong>300+ curated models</strong> across all modalities. Check out Atlas Cloud's new <a href="https://www.atlascloud.ai/console/coding-plan">coding plan promotion</a> for more budget-friendly API access.
</td>
</tr>

<tr>
<td width="25%" align="center" valign="middle">
<a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=2EW65KEQC938">
<img src="static/fenno.png" alt="Fenno.ai Sponsor" width="180">
</a>
</td>
<td width="75%" align="left" valign="middle">
Fenno.ai is a stable and efficient API relay service provider, currently focused on Codex relay services. It is compatible with OpenAI and Anthropic protocols, can flexibly integrate with mainstream coding tools such as Codex, Claude Code, and OpenCode, and can reliably support enterprise-scale demand of hundreds of billions of tokens per day. It supports corporate settlement and invoicing for both domestic and overseas entities. Fenno.ai provides exclusive benefits for CC-Connect users: <a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=2EW65KEQC938">subscribe via this link</a> to get the value Coding Plan at <strong>9.9 RMB for $150 quota</strong>, and earn up to <strong>20% rewards</strong> by inviting friends.
</td>
</tr>
<tr>
<td width="25%" align="center" valign="middle">
<a href="https://s.qiniu.com/FRF7bq">
<img src="static/qiniu.png" alt="Qiniu Cloud AI Sponsor" width="180">
</a>
</td>
<td width="75%" align="left" valign="middle">
Qiniu Cloud AI is an <strong>enterprise-grade large-model MaaS platform</strong> under Qiniu Cloud (02567.HK). It offers one-stop access to <strong>150+ mainstream global models</strong>, is compatible with major model provider protocols, and covers full-modal capabilities including text, image, audio, video, and file processing, serving more than 1.69 million enterprise and developer users. Exclusive benefit: enterprise users can <a href="https://s.qiniu.com/FRF7bq">claim <strong>12 million tokens</strong> for free</a>, and can earn up to <strong>tens of billions of tokens</strong> by inviting friends.
</td>
</tr>
<tr>
<td width="25%" align="center" valign="middle">
<img src="static/wechat.png" alt="Sponsor Contact" width="150">
</td>
<td width="75%" align="left" valign="middle">
<strong>Become a Sponsor</strong><br>
If you would like to sponsor this project, please scan the WeChat QR code on the left (Please state your intent: <strong>Sponsorship</strong>).
</td>
</tr>
</table>

---

🚀 Overview

AIClient2API is an API proxy service that breaks through client limitations, converting free large models originally restricted to client use only (such as Gemini, Antigravity, Codex, Grok, Kiro) into standard OpenAI-compatible interfaces that can be called by any application. Built on Node.js, it supports intelligent conversion between OpenAI, Claude, and Gemini protocols, enabling tools like Cherry-Studio, NextChat, and Cline to freely use advanced models such as Claude Opus and Gemini Pro at scale. The project adopts a modular architecture based on strategy and adapter patterns, with built-in account pool management, intelligent polling, automatic failover, and health check mechanisms, ensuring 99.9% service availability.

NOTE

🎉 Important Milestone


> - Thanks to Ruan Yifeng for the recommendation in Weekly Issue 359

> 📅 Version Update Log

> <details>

<summary>Click to expand detailed version history</summary>

> - 2026.06.03 - Added Grok Build (Grok CLI) support: integrated the grok-cli-oauth xAI OAuth / Responses API flow, covering Grok Build text models, multi-protocol conversion, built-in tools (web search, X search, code interpreter, collections/file attachments), and image/video generation models.

- 2026.05.04 (v3.0.0) - Milestone Update: Deep AI Integration & Self-Discovery Architecture. Added automated Skill guides and remote /api/help, /api/example endpoints, enabling AI agents to seamlessly understand and operate 50+ full API endpoints; achieved full unification of CLI and REST API output results with enhanced structured JSON support.

- 2026.04.29 - Comprehensive support for OpenAI standard Image Generation (/v1/images/generations) and Image Editing (/v1/images/edits) interfaces. Supports automatic conversion from OpenAI format to native image generation protocols of various models, fully compatible with provider pool polling and retry mechanisms, significantly improving the stability of multimodal creation.

- 2026.03.02 - Added Grok protocol support, supporting access to xAI Grok series models (Grok) via Cookie/SSO, supporting multimodal input, image/video generation, automatic token refresh and streaming output

- 2026.01.26 - Added Codex protocol support: supports OpenAI Codex OAuth authorization access

- 2026.01.25 - Enhanced AI Monitor plugin: supports monitoring request parameters and responses before and after AI protocol conversion. Optimized log management: unified log format, visual configuration

- 2026.01.15 - Optimized provider pool manager: added async refresh queue mechanism, buffer queue deduplication, global concurrency control, node warmup and automatic expiry detection

> - 2026.01.03 - Added theme switching functionality and optimized provider pool initialization, removed the fallback strategy of using provider default configuration

- 2025.12.30 - Added main process management and automatic update functionality

- 2025.12.25 - Unified configuration management: All configs centralized to configs/ directory. Docker users need to update mount path to -v "local_path:/app/configs"

- 2025.12.11 - Automatically built Docker images are now available on Docker Hub: justlikemaki/aiclient-2-api

- 2025.11.30 - Added Antigravity protocol support, enabling access to Gemini Pro, Claude Sonnet, and other models via Google internal interfaces

- 2025.11.11 - Added Web UI management console, supporting real-time configuration management and health status monitoring

- 2025.11.06 - Added support for Gemini Preview, enhanced model compatibility and performance optimization

- 2025.10.18 - Kiro open registration, new accounts get 500 credits, full support for Claude Sonnet

- 2025.08.29 - Released account pool management feature, supporting multi-account polling, intelligent failover, and automatic degradation strategies

- Configuration: Add PROVIDER_POOLS_FILE_PATH parameter in configs/config.json

- Reference configuration: provider_pools.json

- History Developed

- Support Gemini CLI, Kiro and other client2API

- OpenAI, Claude, Gemini three-protocol mutual conversion, automatic intelligent switching

</details>

---

💡 Core Advantages

🤖 AI-First, Agent Interaction Support

AI-First Design: This project natively supports efficient interaction with mainstream AI Agents such as OpenClaw, Hermes, and Claude Code.

> 💡 Quick Command: You can tell the AI this sentence directly, and it will automatically master all usage of this project:

> - Remote Deployment:

``text

Please load and learn the Skill in https://raw.githubusercontent.com/justlovemaki/AIClient2API/main/docs/skills/aiclient-cli-usage.md (Service Address: your actual domain or IP, Login Password: your actual password) to master all usage of AIClient2API.

`

- Local Mode:

If you are running the AI agent directly in your local environment, just send:

`text

Please load and learn the Skill in docs/skills/aiclient-cli-usage.md to help me start, configure, and manage the AIClient2API service locally.

`

🎯 Unified Access, One-Stop Management


* Multi-Model Unified Interface: Through standard OpenAI-compatible protocol, configure once to access mainstream large models including Gemini, Claude, Grok, Codex, Kimi, MiniMax
* Flexible Switching Mechanism: Path routing, support dynamic model switching via startup parameters or environment variables to meet different scenario requirements
* Zero-Cost Migration: Fully compatible with OpenAI API specifications, tools like Cherry-Studio, NextChat, Cline can be used without modification
* Multi-Protocol Intelligent Conversion: Support intelligent conversion between OpenAI, Claude, and Gemini protocols for cross-protocol model invocation

🚀 Break Through Limitations, Improve Efficiency


* Bypass Official Restrictions: Utilize OAuth authorization mechanism to effectively break through rate and quota limits of services like Gemini, Antigravity
* TLS Fingerprint Bypass: Built-in TLS Sidecar (Go uTLS) to simulate browser features, effectively bypassing Cloudflare 403 blocks for services like Grok
* Free Advanced Models: Use Claude Opus for free via Kiro API mode, reducing usage costs
* Intelligent Account Pool Scheduling: Support multi-account polling, automatic failover, and configuration degradation, ensuring 99.9% service availability

🛡️ Secure and Controllable, Data Transparent


* Full-Chain Log Recording: Capture all request and response data, supporting auditing and debugging
* Private Dataset Construction: Quickly build proprietary training datasets based on log data
* System Prompt Management: Support override and append modes, achieving perfect combination of unified base instructions and personalized extensions

🔧 Developer-Friendly, Easy to Extend


* Web UI Management Console: Real-time configuration management, health status monitoring, API testing and log viewing
* Modular Architecture: Based on strategy and adapter patterns, adding new model providers requires only 3 steps
* Complete Test Coverage: Integration and unit test coverage 90%+, ensuring code quality
* Containerized Deployment: Provides Docker support, one-click deployment, cross-platform operation

---

📑 Quick Navigation

- 💡 Core Advantages
- 🚀 Quick Start
- 🐳 Docker Deployment
- 📋 Core Features
- 🔐 Authorization Configuration Guide
- 📁 Authorization File Storage Paths
- ⚙️ Advanced Configuration
- ❓ FAQ
- 📄 Open Source License
- 🙏 Acknowledgements
- ⚠️ Disclaimer

---

🔧 Usage Instructions

🚀 Quick Start

The most recommended way to use AIClient2API is to start it through an automated script and configure it visually directly in the Web UI console.

#### 🐳 Docker Quick Start (Recommended)

bash
docker run -d -p 3000:3000 -p 8085-8086:8085-8086 -p 1455:1455 -p 56121:56121 -p 19876-19880:19876-19880 --restart=always -v "your_path/configs:/app/configs" -v "your_path/plugins:/app/src/plugins-user" --name aiclient2api justlikemaki/aiclient-2-api

Parameter Description:
-
-d: Run container in background
-
-p 3000:3000 ...: Port mapping. 3000 is for Web UI, others are for OAuth callbacks (Gemini: 8085, Antigravity: 8086, Codex: 1455, Grok CLI: 56121, Kiro: 19876-19880)
-
--restart=always: Container auto-restart policy
-
-v "your_path/configs:/app/configs": Mount configuration directory (replace "your_path" with actual path, e.g., /home/user/aiclient2api)
-
-v "your_path/plugins:/app/src/plugins-user": Mount user plugins directory
-
--name aiclient2api: Container name

#### 🐳 Docker Compose Deployment

You can also use Docker Compose for deployment. First, navigate to the docker directory:

bash
cd docker
mkdir -p configs
docker compose up -d

To build from source instead of using the pre-built image, edit docker-compose.yml:
1. Comment out the
image: justlikemaki/aiclient-2-api:latest line
2. Uncomment the
build: section
3. Run
docker compose up -d --build

#### 1. Run the startup script
* Linux/macOS:
chmod +x install-and-run.sh && ./install-and-run.sh
* Windows: Double-click
install-and-run.bat

💡 Manual installation and startup (supports custom parameters):

`bash

npm install

# Default startup

npm start

# Show help information

npm run help

# Show API calling examples

npm run example:api

# Backend-only mode (disable frontend management UI)

npm start -- --no-ui

`

#### 2. Access the console
After the server starts, open your browser and visit:
👉 http://localhost:3000

Default Password: admin123 (can be changed in the console or by modifying the pwd file after login)

#### 3. Visual Configuration (Recommended)
Go to the "Configuration" page, you can:
* ✅ Fill in the API Key for each provider or upload OAuth credential files
* ✅ Switch default model providers in real-time
* ✅ Monitor health status and real-time request logs

#### 4. Local Environment Preparation (Non-Docker Users)s
If you are running directly on your local machine (via script or Node.js) and need to bypass TLS detection for services like Grok, please ensure:
* ✅ Install Go Language: Go to the official Go website to download and install (1.20+).
* ✅ Manually Compile Sidecar: Execute the following command to compile the TLS proxy component:

bash
cd tls-sidecar && go build -o tls-sidecar && cd ..

Note: If this binary file is not compiled, the TLS Sidecar feature will fail to start as it cannot find the executable.

#### Script Execution Example

text
========================================
AI Client 2 API Quick Install Script
========================================

[Check] Checking if Node.js is installed...
✅ Node.js is installed, version: v20.10.0
✅ Found package.json file
✅ node_modules directory already exists
✅ Project file check completed

========================================
Starting AI Client 2 API Server...
========================================

🌐 Server will start on http://localhost:3000
📖 Visit http://localhost:3000 to view management interface
⏹️ Press Ctrl+C to stop server

💡 Tip: The script will automatically install dependencies and start the server. If you encounter any issues, the script provides clear error messages and suggested solutions.

---

📋 Core Features

#### Web UI Management Console

A functional Web management interface, including:

📊 Dashboard: System overview, interactive routing examples, client configuration guide

⚙️ Configuration: Real-time parameter modification, supporting all providers (Gemini, Antigravity, OpenAI, Claude, Kiro), including advanced settings and file uploads

🔗 Provider Pools: Monitor active connections, provider health statistics, enable/disable management

📁 Config Files: Centralized OAuth credential management, supporting search filtering and file operations

📜 Real-time Logs: Real-time display of system and request logs, with management controls

🔐 Login Verification: Default password admin123, can be modified via pwd file

Access: http://localhost:3000 → Login → Sidebar navigation → Take effect immediately

#### Multimodal Input Capabilities
Supports various input types such as images and documents, providing you with a richer interaction experience and more powerful application scenarios.

#### Latest Model Support
Seamlessly support the following latest large models, just configure the corresponding endpoint in Web UI or
configs/config.json:
* Grok / Grok Build - xAI's flagship models, now supported via Grok Cookie/SSO and Grok CLI OAuth, supporting thinking models, Grok Build, built-in tools, image generation, and video generation
* Claude Opus - Anthropic's strongest model ever, now supported via Kiro, Antigravity
* Gemini Pro - Google's next-generation architecture preview, now supported via Gemini, Antigravity
* Kimi / MiniMax - Synchronized support for top domestic flagship models, now supported via custom OpenAI, Claude

---

🔐 Authorization Configuration Guide

<details>
<summary>Click to expand detailed authorization configuration steps for each provider</summary>

💡 Tip: For the best experience, it is recommended to manage authorization visually through the Web UI console.

#### 🌐 Web UI Quick Authorization (Recommended)
In the Web UI management interface, you can complete authorization configuration rapidly:
1. Generate Authorization: On the "Provider Pools" page or "Configuration" page, click the "Generate Authorization" button in the upper right corner of the corresponding provider (e.g., Gemini).
2. Scan/Login: An authorization dialog will pop up, you can click "Open in Browser" for login verification. For Gemini and Antigravity, complete the Google account authorization.
3. Auto-Save: After successful authorization, the system will automatically obtain credentials and save them to the corresponding directory in
configs/. You can see the newly generated credentials on the "Config Files" page.
4. Visual Management: You can upload or delete credentials at any time in the Web UI, or use the "Quick Associate" function to bind existing credential files to providers with one click.

#### Gemini CLI OAuth Configuration
1. Obtain OAuth Credentials: Visit Google Cloud Console to create a project and enable Gemini API
2. Project Configuration: You may need to provide a valid Google Cloud project ID, which can be specified via the startup parameter
--project-id
3. Ensure Project ID: When configuring in the Web UI, ensure the project ID entered matches the project ID displayed in the Google Cloud Console and Gemini CLI.

#### Antigravity OAuth Configuration
1. Personal Account: Personal accounts require separate authorization, application channels have been closed.
2. Pro Member: Antigravity is temporarily open to Pro members, you need to purchase a Pro membership first.
3. Organization Account: Organization accounts require separate authorization, contact the administrator to obtain authorization.

#### Kiro API Configuration
1. Environment Preparation: Download and install Kiro client
2. Complete Authorization: Log in to your account in the client to generate
kiro-auth-token.json credential file
3. Best Practice: Recommended to use with Claude Code for optimal experience
4. Important Notice: Kiro service usage policy has been updated, please visit the official website for the latest usage restrictions and terms

#### Kiro Extended Thinking (Claude Models)
AIClient2API supports Kiro extended thinking when using Claude-compatible requests (
/v1/messages) or OpenAI-compatible requests (/v1/chat/completions) routed to claude-kiro-oauth.

Claude-compatible (/v1/messages):

bash
curl http://localhost:3000/claude-kiro-oauth/v1/messages \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"thinking": { "type": "enabled", "budget_tokens": 10000 },
"messages": [{ "role": "user", "content": "Solve this step by step." }]
}'

OpenAI-compatible (/v1/chat/completions):

bash
curl http://localhost:3000/claude-kiro-oauth/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key" \
-d '{
"model": "claude-sonnet-4-5",
"messages": [{ "role": "user", "content": "Solve this step by step." }],
"extra_body": {
"anthropic": {
"thinking": { "type": "enabled", "budget_tokens": 10000 }
}
}
}'

Adaptive mode:
- Claude:
"thinking": { "type": "adaptive", "effort": "high" }
- OpenAI:
"extra_body.anthropic.thinking": { "type": "adaptive", "effort": "high" }

Notes:
-
budget_tokens is clamped to [1024, 24576] (default 20000 if omitted/invalid).
- Token acquisition/refresh/pool rotation is unchanged.

#### Codex OAuth Configuration
1. Generate Authorization: On the Web UI "Provider Pools" or "Configuration" page, click the "Generate Authorization" button for Codex
2. Browser Login: The system opens the OpenAI Codex authorization page to complete OAuth login
3. Auto Save: After successful authorization, the system automatically saves the Codex OAuth credential file
4. Callback Port: Ensure the OAuth callback port
1455 is not occupied

#### Grok CLI OAuth Configuration
1. Generate Authorization: On the Web UI "Provider Pools" or "Configuration" page, click the "Generate Authorization" button for Grok CLI
2. Browser Login: The system opens the xAI authorization page to complete OAuth login
3. Auto Save: After successful authorization, the system automatically saves the Grok CLI OAuth credential file to
configs/grok-cli/
4. Callback Port: Ensure the OAuth callback port
56121 is not occupied

#### Grok Cookie/SSO Configuration
1. Obtain SSO Token: Log in to the Grok official website, copy the value of
sso from Application -> Cookies in browser developer tools
2. Enter Configuration: In the Web UI "Configuration" page or directly modify the configuration file, enter the token into
GROK_COOKIE_TOKEN
3. Supported Features:
- Chat and Thinking models (Grok Thinking)
- Image generation (Grok Imagine)
- Video generation (Grok Video)
4. Notes: Ensure
GROK_USER_AGENT matches the browser used when obtaining the cookie to avoid being blocked

#### Account Pool Management Configuration
1. Create Pool Configuration File: Create a configuration file referencing provider_pools.json.example
2. Configure Pool Parameters: Set
PROVIDER_POOLS_FILE_PATH in configs/config.json to point to the pool configuration file
3. Startup Parameter Configuration: Use the
--provider-pools-file <path> parameter to specify the pool configuration file path
4. Health Check: The system will automatically perform periodic health checks and avoid using unhealthy providers

</details>

📁 Authorization File Storage Paths

<details>
<summary>Click to expand default storage locations for authorization credentials</summary>

Default storage locations for authorization credential files of each service:

| Service | Default Path | Description |
|------|---------|------|
| Gemini |
~/.gemini/oauth_creds.json | OAuth authentication credentials |
| Kiro |
~/.aws/sso/cache/kiro-auth-token.json | Kiro authentication token |
| Antigravity |
~/.antigravity/oauth_creds.json | Antigravity OAuth credentials (supports Claude Opus) |
| Codex |
~/.codex/oauth_creds.json | Codex OAuth credentials |
| Grok CLI |
configs/grok-cli/..._xai-..._oauth_creds.json | Grok CLI OAuth credentials |

Note: ~ represents the user home directory (Windows: C:\Users\username, Linux/macOS: /home/username or /Users/username)

Custom Path: Can specify custom storage location via relevant parameters in configuration file or environment variables

</details>

---

Advanced Configuration

<details>
<summary>Click to expand proxy configuration, model filtering, and Fallback advanced settings</summary>

#### 1. Proxy Configuration

This project supports flexible proxy configuration, allowing you to configure a unified proxy for different providers or use provider-specific proxied endpoints.

Configuration Methods:

1. Web UI Configuration (Recommended): Convenient configuration management

In the "Configuration" page of the Web UI, you can visually configure all proxy options:
- Unified Proxy: Fill in the proxy address in the "Proxy Settings" area and check the providers that need to use the proxy
- Provider Endpoints: In each provider's configuration area, directly modify the Base URL to a proxied endpoint
- Click "Save Configuration": Takes effect immediately without restarting the service

2. Unified Proxy Configuration: Configure a global proxy and specify which providers use it

- Web UI Configuration: Fill in the proxy address in the "Proxy Settings" area of the "Configuration" page and check the providers that need to use the proxy
- Configuration File: Configure in
configs/config.json

json
{
"PROXY_URL": "http://127.0.0.1:7890",
"PROXY_ENABLED_PROVIDERS": [
"gemini-cli-oauth",
"gemini-antigravity",
"claude-kiro-oauth",
"grok-web"
]
}


3. Provider-Specific Proxied Endpoints: Some providers (like OpenAI, Claude) support configuring proxied API endpoints

- Web UI Configuration: In each provider's configuration area on the "Configuration" page, modify the corresponding Base URL
- Configuration File: Configure in
configs/config.json

json
{
"OPENAI_BASE_URL": "https://your-proxy-endpoint.com/v1",
"CLAUDE_BASE_URL": "https://your-proxy-endpoint.com"
}

Supported Proxy Types:
- HTTP Proxy:
http://127.0.0.1:7890
- HTTPS Proxy:
https://127.0.0.1:7890
- SOCKS5 Proxy:
socks5://127.0.0.1:1080

Use Cases:
- Network-Restricted Environments: Use in network environments where Google, OpenAI, and other services cannot be accessed directly
- Hybrid Configuration: Some providers use unified proxy, others use their own proxied endpoints
- Flexible Switching: Enable/disable proxy for specific providers at any time in the Web UI

Notes:
- Proxy configuration priority: Unified proxy configuration > Provider-specific endpoints > Direct connection
- Ensure the proxy service is stable and available, otherwise it may affect service quality
- SOCKS5 proxy usually performs better than HTTP proxy

#### 2. Model Filtering Configuration

Support excluding unsupported models through notSupportedModels configuration, the system will automatically skip these providers.

Configuration: Add notSupportedModels field for providers in configs/provider_pools.json:

json
{
"gemini-cli-oauth": [
{
"uuid": "provider-1",
"notSupportedModels": ["gemini-3.0-pro", "gemini-3.5-flash"],
"checkHealth": true
}
]
}

How It Works:
- When requesting a specific model, the system automatically filters out providers that have configured the model as unsupported
- Only providers that support the model will be selected to handle the request

Use Cases:
- Some accounts cannot access specific models due to quota or permission restrictions
- Need to assign different model access permissions to different accounts

#### 3. Cross-Type Fallback Configuration

When all accounts under a Provider Type (e.g., gemini-cli-oauth) are exhausted due to 429 quota limits or marked as unhealthy, the system can automatically fallback to another compatible Provider Type (e.g., gemini-antigravity) instead of returning an error directly.

Configuration: Add providerFallbackChain configuration in configs/config.json:

json
{
"providerFallbackChain": {
"gemini-cli-oauth": ["gemini-antigravity"],
"gemini-antigravity": ["gemini-cli-oauth"],
"claude-kiro-oauth": ["claude-custom"],
"claude-custom": ["claude-kiro-oauth"]
}
}

How It Works:
1. Try to select a healthy account from the primary Provider Type pool
2. If all accounts in that type are unhealthy or return 429:
- Look up the configured fallback types
- Check if the fallback type supports the requested model (protocol compatibility check)
- Select a healthy account from the fallback type's pool
3. Supports multi-level degradation chains:
gemini-cli-oauth → gemini-antigravity → openai-custom
4. Only returns an error if all fallback types are also unavailable

Use Cases:
- In batch task scenarios, the free RPD quota of a single Provider Type can be easily exhausted in a short time
- Through cross-type Fallback, you can fully utilize the independent quotas of multiple Providers, improving overall availability and throughput

Notes:
- Fallback only occurs between protocol-compatible types (e.g., between
gemini-, between claude-)
- The system automatically checks if the target Provider Type supports the requested model

#### 4. TLS Sidecar (Bypass 403/Cloudflare)

For services like Grok that strictly validate TLS fingerprints (JA3/JA4), this project integrates a Sidecar proxy based on Go uTLS, which effectively solves 403 Forbidden errors by simulating browser TLS features.

Configuration Instructions:

1. Compile the Binary:
Since TLS simulation requires Go language support, you need to compile the sidecar first:

bash
cd tls-sidecar
go build -o tls-sidecar

Windows users, after compiling, ensure the generated
tls-sidecar.exe is located in the tls-sidecar/ or the root directory.

2. Enable Configuration:
Enable TLS Sidecar in the "Configuration" page of the Web UI, or modify
configs/config.json:

json
{
"TLS_SIDECAR_ENABLED": true,
"TLS_SIDECAR_PORT": 9090
}

3. How It Works:
- When enabled, the system automatically starts and manages the Go process.
- Requests for specific providers (like Grok) are automatically routed to the Sidecar.
- The Sidecar uses the latest Chrome fingerprint for TLS handshakes and supports automatic HTTP/2 negotiation.

Notes:
- Local running requires a Go environment (1.20+).
- Docker Users: The image already includes the pre-compiled binary; just enable it in the configuration, no manual compilation required.

</details>

---

❓ FAQ

<details>
<summary>Click to expand FAQ and solutions (port occupation, Docker startup, 429 errors, etc.)</summary>

1. OAuth Authorization Failed

Problem Description: After clicking "Generate Authorization", the browser opens the authorization page but authorization fails or cannot be completed.

Solutions:
- Check Network Connection: Ensure you can access Google, Alibaba Cloud, and other services normally
- Check Port Occupation: OAuth callbacks require specific ports (Gemini: 8085, Antigravity: 8086, Codex: 1455, Grok CLI: 56121, Kiro: 19876-19880), ensure these ports are not occupied
- Clear Browser Cache: Try using incognito mode or clearing browser cache and retry
- Check Firewall Settings: Ensure the firewall allows access to local callback ports
- Docker Users: Ensure all OAuth callback ports are correctly mapped

2. Port Already in Use

Problem Description: When starting the service, it shows the port is already in use (e.g., EADDRINUSE).

Solutions:

bash

Windows - Find the process occupying the port


netstat -ano | findstr :3000

Then use Task Manager to end the corresponding PID process

Linux/macOS - Find and end the process occupying the port


lsof -i :3000
kill -9 <PID>

Or modify the port configuration in configs/config.json to use a different port.

3. Docker Container Won't Start

Problem Description: Docker container fails to start or exits immediately.

Solutions:
- Check Logs:
docker logs aiclient2api to view error messages
- Check Mount Path: Ensure the local path in the
-v parameter exists and has read/write permissions
- Check Port Conflicts: Ensure all mapped ports are not occupied on the host
- Re-pull Image:
docker pull justlikemaki/aiclient-2-api:latest

4. Credential File Not Recognized

Problem Description: After uploading or configuring credential files, the system shows it cannot be recognized or format error.

Solutions:
- Check File Format: Ensure the credential file is valid JSON format
- Check File Path: Ensure the file path is correct, Docker users need to ensure the file is in the mounted directory
- Check File Permissions: Ensure the service has permission to read the credential file
- Regenerate Credentials: If credentials have expired, try re-authorizing via OAuth

5. Request Returns 429 Error

Problem Description: API requests frequently return 429 Too Many Requests error.

Solutions:
- Configure Account Pool: Add multiple accounts to
provider_pools.json, enable polling mechanism
- Configure Fallback: Configure
providerFallbackChain in config.json for cross-type degradation
- Enable 429 Cooldown: Set
RATE_LIMIT_COOLDOWN_ENABLED to true and tune RATE_LIMIT_COOLDOWN_MS so rate-limited accounts temporarily leave the pool and recover automatically
- Reduce Request Frequency: Appropriately increase request intervals to avoid triggering rate limits
- Wait for Quota Reset: Free quotas usually reset daily or per minute

6. Model Unavailable or Returns Error

Problem Description: When requesting a specific model, it returns an error or shows the model is unavailable.

Solutions:
- Check Model Name: Ensure you're using the correct model name (case-sensitive)
- Check Provider Support: Confirm the currently configured provider supports that model
- Check Account Permissions: Some advanced models may require specific account permissions
- Configure Model Filtering: Use
notSupportedModels to exclude unsupported models

7. Web UI Cannot Be Accessed

Problem Description: Browser cannot open http://localhost:3000.

Solutions:
- Check Service Status: Confirm the service has started successfully, check terminal output
- Check Port Mapping: Docker users ensure
-p 3000:3000 parameter is correct
- Try Other Address: Try accessing
http://127.0.0.1:3000
- Check Firewall: Ensure the firewall allows access to port 3000

8. Streaming Response Interrupted

Problem Description: When using streaming output, the response is interrupted midway or incomplete.

Solutions:
- Check Network Stability: Ensure network connection is stable
- Increase Timeout: Increase request timeout in client configuration
- Check Proxy Settings: If using a proxy, ensure the proxy supports long connections
- Check Service Logs: Check for error messages

9. Configuration Changes Not Taking Effect

Problem Description: After modifying configuration in Web UI, service behavior doesn't change.

Solutions:
- Refresh Page: Refresh the Web UI page after modification
- Check Save Status: Confirm the configuration was saved successfully (check prompt messages)
- Restart Service: Some configurations may require service restart to take effect
- Check Configuration File: Directly check
configs/config.json to confirm changes were written

10. API Returns 404

Solutions:
- Check Endpoint Path: Ensure you're using the correct endpoint path, such as
/v1/chat/completions etc.
- Check Client Auto-completion: Some clients (like Cherry-Studio, NextChat) automatically append paths (like
/v1/chat/completions) after the Base URL, causing path duplication. Check the actual request URL in the console and remove redundant path parts
- Check Service Status: Confirm the service has started normally, visit
http://localhost:3000 to view Web UI
- Check Port Configuration: Ensure requests are sent to the correct port (default 3000)
- View Available Routes: Check "Interactive Routing Examples" on the Web UI dashboard page to see all available endpoints

11. Unauthorized: API key is invalid or missing

Problem Description: When calling API endpoints, it returns Unauthorized: API key is invalid or missing. error.

Solutions:
- Check API Key Configuration: Ensure API Key is correctly configured in
configs/config.json or Web UI
- Check Request Header Format: Ensure the request contains the correct Authorization header format, such as
Authorization: Bearer your-api-key
- Check Service Logs: View detailed error messages on the "Real-time Logs" page in Web UI to locate the specific cause

12. No available and healthy providers for type

Problem Description: When calling API, it returns No available and healthy providers for type xxx error.

Solutions:
- Check Provider Status: Check if providers of the corresponding type are in healthy status on the "Provider Pools" page in Web UI
- Check Credential Validity: Confirm OAuth credentials have not expired; if expired, regenerate authorization
- Check Quota Limits: Some providers may have reached free quota limits; wait for quota reset or add more accounts
- Enable Fallback: Configure
providerFallbackChain in config.json to automatically switch to backup providers when the primary provider is unavailable
- View Detailed Logs: Check specific health check failure reasons on the "Real-time Logs" page in Web UI

13. Request Returns 403 Forbidden Error

Problem Description: API requests return 403 Forbidden error.

Solutions:
- Enable TLS Sidecar: For services like Grok, 403 is often due to TLS fingerprint blocking. Please refer to Advanced Configuration - TLS Sidecar to enable and compile the Sidecar.
- Check Node Status: If you see the node status is normal (health check passed) on the "Provider Pools" page in Web UI, you can ignore this error as the system will handle it automatically
- Check Account Permissions: Confirm the account has permission to access the requested model or service
- Check API Key Permissions: Some providers' API Keys may have access scope restrictions; ensure the Key has sufficient permissions
- Check Regional Restrictions: Some services may have regional access restrictions; try using a proxy or VPN
- Check Credential Status: OAuth credentials may have been revoked or expired; try regenerating authorization
- Check Request Frequency: Some providers have strict request frequency limits; reduce request frequency and retry
- View Provider Documentation: Visit the official documentation of the corresponding provider to understand specific access restrictions and requirements

14. Why should I enable "OAuth Token Auto-Refresh"?

Problem Description: Unsure if token auto-refresh is necessary.

Solution:
OAuth tokens (e.g., Gemini, Antigravity, Codex) typically have a limited lifespan (e.g., 1 hour).
- With it enabled: The system automatically checks and refreshes tokens before they expire in the background. This ensures 24/7 stable API service and avoids
401 Unauthorized or 403 Forbidden errors due to expired tokens.
- Without it: Once a token expires, the system cannot automatically obtain a new one, causing API requests to fail until you manually re-authorize.

15. What is the impact of not enabling "Preload Model Providers" on token maintenance?

Problem Description: Confusion about the "Preload Model Providers" configuration and its relation to token refresh.

Solution:
The system only performs auto-refresh tasks for providers that are loaded into the active pool.
- Impact: If a provider is not checked as a "Preload Model Provider" in the configuration, it won't be initialized when the system starts. Since it's not in the pool, the background refresh task will not process its token.
- Consequence: If you don't use that provider for a long time, its token will expire silently. When you eventually call it via a specific route, the request will fail due to the expired token.
- Recommendation: Always check providers you intend to use frequently and need to keep active in the "Preload Model Providers" list.

</details>

---

📄 Open Source License

This project follows the GNU General Public License v3 (GPLv3) license. For details, please check the LICENSE file in the root directory.

🙏 Acknowledgements

The development of this project was greatly inspired by the official Google Gemini CLI and referenced part of the code implementation of gemini-cli.ts` in Cline 3.18.0. Sincere thanks to the Google official team and the Cline development team for their excellent work!

Contributor List

Thanks to all the developers who contributed to the AIClient2API project:

[](https://github.com/justlovemaki/AIClient-2-API/graphs/contributors)


🌟 Star History


[](https://www.star-history.com/#justlovemaki/AIClient-2-API&Timeline)

---

⚠️ Disclaimer

Usage Risk Warning


This project (AIClient2API) is for learning and research purposes only. Users assume all risks when using this project. The author is not responsible for any direct, indirect, or consequential losses resulting from the use of this project.

Third-Party Service Responsibility Statement


This project is an API proxy tool and does not provide any AI model services. All AI model services are provided by their respective third-party providers (such as Google, OpenAI, Anthropic, etc.). Users should comply with the terms of service and policies of each third-party service when accessing them through this project. The author is not responsible for the availability, quality, security, or legality of third-party services.

Data Privacy Statement


This project runs locally and does not collect or upload any user data. However, users should protect their API keys and other sensitive information when using this project. It is recommended that users regularly check and update their API keys and avoid using this project in insecure network environments.


Users should comply with the laws and regulations of their country/region when using this project. It is strictly prohibited to use this project for any illegal purposes. Any consequences resulting from users' violation of laws and regulations shall be borne by the users themselves.

---