feat(core): 增强网络代理控制与 OAuth 凭证管理能力

核心改进:
- 实现 HTTP 客户端代理可配置化,新增 USE_SYSTEM_PROXY_* 系列开关
- 引入 CredentialsClearRequiredError 异常,优化 Qwen 令牌过期处理流程
- 重构 provider-pool-manager 配置传递,支持全局代理设置继承
- 封装 commonFetch 统一方法,规范 fetch 和 axios 的代理行为

文档更新:
- 三语言 README 全面改版,突出协议转换和免费模型使用价值
- 新增授权配置分步指南,覆盖 Gemini/Qwen/Kiro 完整流程
- 补充 Path 路由切换表格,明确各提供商适用场景
- 修正 OpenAI Responses API 标识符拼写错误
This commit is contained in:
hex2077 2025-10-22 21:04:14 +08:00
parent 06eacb0419
commit 6b0c323dfe
10 changed files with 663 additions and 440 deletions

View file

@ -14,36 +14,57 @@
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
[![Node.js](https://img.shields.io/badge/Node.js-≥20.0.0-green.svg)](https://nodejs.org/)
[![docker](https://img.shields.io/badge/docker-≥20.0.0-green.svg)](https://aiproxy.justlikemaki.vip/en/docs/installation/docker-deployment.html)
[![Docker](https://img.shields.io/badge/docker-≥20.0.0-blue.svg)](https://aiproxy.justlikemaki.vip/en/docs/installation/docker-deployment.html)
[**中文**](./README.md) | [**English**](./README-EN.md) | [**日本語**](./README-JA.md) | [**More Detailed Documentation**](https://aiproxy.justlikemaki.vip/en/)
[**中文**](./README.md) | [**English**](./README-EN.md) | [**日本語**](./README-JA.md) | [**📚 Complete Documentation**](https://aiproxy.justlikemaki.vip/en/)
</div>
`AIClient2API` is a versatile and lightweight API proxy designed for developers, providing abundant free API request quotas and comprehensive support for mainstream large models including Google Gemini, Qwen Code, and Claude. It transforms various backend APIs into a standard OpenAI format interface via a Node.js HTTP server. The project features a modern, modular architecture, supporting strategy and adapter patterns, complete with comprehensive test coverage and health check mechanisms. It's ready to use out-of-the-box: simply `npm install` and run. You can easily switch between model providers in the configuration file, allowing any OpenAI-compatible client or application to seamlessly use different large model capabilities through the same API address, eliminating the hassle of maintaining multiple configurations and dealing with incompatible interfaces for different services.
`AIClient2API` is an API proxy service that breaks through client limitations, converting free large models originally restricted to client use only (such as Gemini CLI, Qwen Code Plus, Kiro Claude) into standard OpenAI-compatible interfaces that can be called by any application. Built on Node.js, it supports intelligent conversion between three major protocols (OpenAI, Claude, Gemini), enabling tools like Cherry-Studio, NextChat, and Cline to freely use advanced models such as Claude Sonnet 4.5, Gemini 2.5 Flash, and Qwen3 Coder Plus 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]
> Thanks to Ruan Yifeng for the recommendation in [Weekly Issue 359](https://www.ruanyifeng.com/blog/2025/08/weekly-issue-359.html).
> **🎉 Important Milestone**
>
> 8.29 Added account pool mode, which supports multiple accounts for all providers, with built-in polling, failover (requires client retry), and configuration degradation. Requires adding PROVIDER_POOLS_FILE_PATH to config, see the configuration file: provider_pools.json for details.
> - Thanks to Ruan Yifeng for the recommendation in [Weekly Issue 359](https://www.ruanyifeng.com/blog/2025/08/weekly-issue-359.html)
>
> 9.1 Added Qwen Code CLI support, can use qwen3-coder-plus model
>
> 10.18 Kiro open registration, new accounts get 500 credits, now supports Claude Sonnet4.5
> **📅 Version Update Log**
>
> - **2025.10.18** - Kiro open registration, new accounts get 500 credits, full support for Claude Sonnet 4.5
> - **2025.09.01** - Integrated Qwen Code CLI, added `qwen3-coder-plus` model support
> - **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 config.json
> - Reference configuration: [provider_pools.json](./provider_pools.json.example)
---
## 💡 Core Advantages
* ✅ **Unified Access to Multiple Models**: One interface to access Gemini, OpenAI, Claude, Kimi K2, GLM-4.5, Qwen Code, and other cutting-edge models. Freely switch between different model providers using simple startup parameters or request headers.
* ✅ **Bypass Official Restrictions**: By supporting Gemini CLI's OAuth authorization method, it effectively circumvents the rate and quota limits of official free APIs, granting you higher request quotas and usage frequency.
* ✅ **Bypass Client Restrictions**: Kiro API mode supports free usage of the Claude Sonnet 4.5 model.
* ✅ **Seamless OpenAI Compatibility**: Provides an interface fully compatible with the OpenAI API, enabling your existing toolchains and clients (e.g., LobeChat, NextChat) to integrate all supported models at zero cost.
* ✅ **Intelligent Account Pool Management**: Supports multi-account polling, failover, and configuration degradation, ensuring high service availability and effectively avoiding single account limitations.
* ✅ **Enhanced Controllability**: Powerful logging features allow you to capture and record all request prompts, facilitating auditing, debugging, and building private datasets.
* ✅ **Extremely Easy to Extend**: Thanks to the new modular and strategy pattern design, adding a new model provider has never been simpler.
* ✅ **Comprehensive Test Coverage**: Provides extensive integration and unit tests, ensuring the stability and reliability of all API endpoints and features.
* ✅ **Docker Support**: Provides complete Docker containerization support for rapid deployment and environment isolation.
### 🎯 Unified Access, One-Stop Management
* **Multi-Model Unified Interface**: Through standard OpenAI-compatible protocol, configure once to access mainstream large models including Gemini, Claude, GPT, Qwen Code, Kimi K2, GLM-4.6
* **Flexible Switching Mechanism**: Support dynamic model switching via startup parameters, Path routing, 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
* Call Claude models using OpenAI protocol: Use `claude-custom` or `claude-kiro-oauth` providers
* Call Gemini models using OpenAI protocol: Use `gemini-cli-oauth` provider
* Call Gemini models using Claude protocol: Use `gemini-cli-oauth` provider
* Call OpenAI models using Claude protocol: Use `openai-custom` or `openai-qwen-oauth` providers
### 🚀 Break Through Limitations, Improve Efficiency
* **Bypass Official Restrictions**: Utilize OAuth authorization mechanism to effectively break through rate and quota limits of free APIs like Gemini
* **Free Advanced Models**: Use Claude Sonnet 4.5 for free via Kiro API mode, use Qwen3 Coder Plus via Qwen OAuth 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
* **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
* **MCP Protocol Support**: Perfectly compatible with Model Context Protocol, easily extend functionality
---
@ -52,8 +73,6 @@
- [🐳 Docker Deployment](https://aiproxy.justlikemaki.vip/en/docs/installation/docker-deployment.html)
- [🎨 Model Protocol and Provider Relationship Diagram](#-model-protocol-and-provider-relationship-diagram)
- [🔧 Usage Instructions](#-usage-instructions)
- [💻 Proxy Settings](#-proxy-settings)
- [🌟 Special Usage & Advanced Tips](#-special-usage--advanced-tips)
- [🚀 Project Startup Parameters](#-project-startup-parameters)
- [📄 Open Source License](#-open-source-license)
- [🙏 Acknowledgements](#-acknowledgements)
@ -63,9 +82,13 @@
## 🎨 Model Protocol and Provider Relationship Diagram
- OpenAI Protocol (P_OPENAI): Supports all MODEL_PROVIDERs, including openai-custom, gemini-cli-oauth, claude-custom, claude-kiro-oauth and openai-qwen-oauth.
- Claude Protocol (P_CLAUDE): Supports claude-custom, claude-kiro-oauth, gemini-cli-oauth, openai-custom and openai-qwen-oauth.
- Gemini Protocol (P_GEMINI): Supports gemini-cli-oauth.
This project supports multiple model providers through different protocols. The following is an overview of their relationships:
* **OpenAI Protocol (P_OPENAI)**: Implemented by `openai-custom`, `gemini-cli-oauth`, `claude-custom`, `claude-kiro-oauth`, and `openai-qwen-oauth` model providers.
* **Claude Protocol (P_CLAUDE)**: Implemented by `claude-custom`, `claude-kiro-oauth`, `gemini-cli-oauth`, `openai-custom`, and `openai-qwen-oauth` model providers.
* **Gemini Protocol (P_GEMINI)**: Implemented by `gemini-cli-oauth` model provider.
Detailed relationship diagram:
```mermaid
@ -108,123 +131,123 @@
## 🔧 Usage Instructions
* **MCP Support**: While the built-in command functions of the original Gemini CLI are unavailable, this project fully supports MCP (Model Context Protocol), enabling powerful functional extensions when paired with MCP-compatible clients.
* **Multimodal Capabilities**: Supports multimodal inputs like images and documents, offering a richer interactive experience.
* **Latest Model Support**: Supports the latest **Kimi K2**, **GLM-4.5** and **Qwen Code** models. Simply configure the corresponding OpenAI or Claude compatible interfaces in `config.json` for use.
* **Qwen Code Support**: Using Qwen Code will automatically open an authorization page in the browser. After completing authorization, it will generate an `oauth_creds.json` file in the `~/.qwen` directory. Please use the official default parameters temperature=0 and top_p=1.
* **Kiro API**: Using the Kiro API requires [downloading the Kiro client](https://aibook.ren/archives/kiro-install) and completing authorized login to generate `kiro-auth-token.json`. **Recommended for optimal experience with Claude Code**. Note: Kiro service policy has been adjusted, please check official announcements for specific usage limitations.
* **Using Different Providers in Claude Code**: Via Path routing, you can use different providers in Claude-related API calls:
* `http://localhost:3000/claude-custom` - Use the Claude API provider defined in the configuration file
* `http://localhost:3000/claude-kiro-oauth` - Access the Claude API using Kiro OAuth authentication
* `http://localhost:3000/openai-custom` - Use the OpenAI custom provider to handle Claude requests
* `http://localhost:3000/gemini-cli-oauth` - Use the Gemini CLI OAuth provider to handle Claude requests
* `http://localhost:3000/openai-qwen-oauth` - Use the Qwen OAuth provider to handle Claude requests
* Each provider can be configured with different API keys, base URLs, and other parameters for flexible provider switching
### 📋 Core Features
These Path routes can not only be used in direct API calls but also in programming agents like Cline and Kilo. By specifying different paths, you can invoke the corresponding models. For example, when configuring API endpoints in a programming agent, you can use `http://localhost:3000/claude-kiro-oauth` to invoke the Claude model authenticated via Kiro OAuth, or use `http://localhost:3000/gemini-cli-oauth` to invoke the Gemini model.
#### MCP Protocol Support
This project is fully compatible with **Model Context Protocol (MCP)**, enabling seamless integration with MCP-supporting clients for powerful functional extensions.
Besides switching providers via Path routing, you can also configure Claude parameters by setting environment variables. For instance, when using the `http://localhost:3000/claude-custom` path route, you can configure via the following environment variables:
#### Multimodal Input Capabilities
Supports various input types including images and documents, providing richer interactive experiences and more powerful application scenarios.
* `ANTHROPIC_BASE_URL`: Set the base URL path for the Claude API
* `ANTHROPIC_AUTH_TOKEN`: Set the authentication token for the Claude service
* `ANTHROPIC_MODEL`: Set the Claude model to be used
#### Environment Variable Setting Methods for Different Systems
When using the `http://localhost:3000/claude-custom` path, you can set environment variables as follows:
##### Linux / macOS
```bash
export ANTHROPIC_BASE_URL="http://localhost:3000/claude-custom"
export ANTHROPIC_AUTH_TOKEN="your-auth-token-here"
export ANTHROPIC_MODEL="your-model-name"
```
##### Windows (CMD)
```cmd
set ANTHROPIC_BASE_URL=http://localhost:3000/claude-custom
set ANTHROPIC_AUTH_TOKEN=your-auth-token-here
set ANTHROPIC_MODEL=your-model-name
```
##### Windows (PowerShell)
```powershell
$env:ANTHROPIC_BASE_URL="http://localhost:3000/claude-custom"
$env:ANTHROPIC_AUTH_TOKEN="your-auth-token-here"
$env:ANTHROPIC_MODEL="your-model-name"
```
### Default Authorization File Paths
The following are the default storage paths for authorization files for each service:
* **Gemini**: `~/.gemini/oauth_creds.json`
* **Kiro**: `~/.aws/sso/cache/kiro-auth-token.json`
* **Qwen**: `~/.qwen/oauth_creds.json`
Where `~` represents the user's home directory. If you need to customize the paths, you can set them through configuration files or environment variables.
#### Latest Model Support
Seamlessly supports the following latest large models, simply configure the corresponding OpenAI or Claude compatible interface in [`config.json`](./config.json):
* **Kimi K2** - Moonshot AI's latest flagship model
* **GLM-4.5** - Zhipu AI's latest version
* **Qwen Code** - Alibaba Tongyi Qianwen code-specific model
---
## 💻 Proxy Settings
### 🔐 Authorization Configuration Guide
> **Hint**: If you are using this in an environment where direct access to Google/OpenAI/Claude/Kiro services is unavailable, please set up an HTTP proxy for your terminal first, do not set up an HTTPS proxy.
#### Gemini CLI OAuth Configuration
1. **Obtain OAuth Credentials**: Visit [Google Cloud Console](https://console.cloud.google.com/) to create a project and enable Gemini API
2. **First Authorization**: After using Gemini service, the command line will print Google authorization page, copy the page to browser for authorization, then return to command line
3. **Credential Storage**: After successful authorization, `oauth_creds.json` file will be automatically generated and saved to `~/.gemini` directory
4. **Project Configuration**: Need to provide a valid Google Cloud project ID, can be specified via startup parameter `--project-id`
### HTTP Proxy Setup Commands for Different Terminal Environments
#### Qwen Code OAuth Configuration
1. **First Authorization**: After starting the service, the system will automatically open the authorization page in the browser
2. **Credential Storage**: After successful authorization, `oauth_creds.json` file will be automatically generated and saved to `~/.qwen` directory
3. **Recommended Parameters**: Use official default parameters for best results
```json
{
"temperature": 0,
"top_p": 1
}
```
To ensure `AIClient2API` can access external AI services (e.g., Google, OpenAI, Claude, Kiro), you might need to configure an HTTP proxy in your terminal environment. Here are the proxy setup commands for various operating systems:
#### Kiro API Configuration
1. **Environment Preparation**: [Download and install Kiro client](https://aibook.ren/archives/kiro-install)
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
#### OpenAI Responses API
* **Application Scenario**: Suitable for scenarios requiring structured dialogue using OpenAI Responses API, such as Codex
* **Configuration Method**:
* Method 1: Set `MODEL_PROVIDER` to `openaiResponses-custom` in [`config.json`](./config.json)
* Method 2: Use startup parameter `--model-provider openaiResponses-custom`
* Method 3: Use path routing `/openaiResponses-custom`
* **Required Parameters**: Provide valid API key and base URL
---
### 🔄 Model Provider Switching
This project provides two flexible model switching methods to meet different usage scenario requirements.
#### Method 1: Startup Parameter Switching
Specify the default model provider via command line parameters:
#### Linux / macOS
```bash
export HTTP_PROXY="http://your_proxy_address:port"
# If authentication is required for the proxy
# export HTTP_PROXY="http://username:password@your_proxy_address:port"
```
To make these settings permanent, add them to your shell configuration file (e.g., `~/.bashrc`, `~/.zshrc`, or `~/.profile`).
# Use Gemini provider
node src/api-server.js --model-provider gemini-cli-oauth --project-id your-project-id
#### Windows (CMD)
```cmd
set HTTP_PROXY=http://your_proxy_address:port
:: If authentication is required for the proxy
:: set HTTP_PROXY=http://username:password@your_proxy_address:port
```
These settings are effective only for the current CMD session. For permanent configuration, set them via system environment variables.
# Use Claude Kiro provider
node src/api-server.js --model-provider claude-kiro-oauth
#### Windows (PowerShell)
```powershell
$env:HTTP_PROXY="http://your_proxy_address:port"
# If authentication is required for the proxy
# $env:HTTP_PROXY="http://username:password@your_proxy_address:port"
# Use Qwen provider
node src/api-server.js --model-provider openai-qwen-oauth
```
These settings are effective only for the current PowerShell session. For permanent configuration, add them to your PowerShell profile (`$PROFILE`) or set them via system environment variables.
**Please replace `your_proxy_address` and `port` with your actual proxy address and port.**
**Available Model Provider Identifiers**:
- `openai-custom` - Standard OpenAI API
- `claude-custom` - Official Claude API
- `gemini-cli-oauth` - Gemini CLI OAuth
- `claude-kiro-oauth` - Kiro Claude OAuth
- `openai-qwen-oauth` - Qwen Code OAuth
- `openaiResponses-custom` - OpenAI Responses API
#### Method 2: Path Routing Switching (Recommended)
Achieve instant switching by specifying provider identifier in API request path:
| Route Path | Description | Use Case |
|---------|------|---------|
| `/claude-custom` | Use Claude API from config file | Official Claude API calls |
| `/claude-kiro-oauth` | Access Claude via Kiro OAuth | Free use of Claude Sonnet 4.5 |
| `/openai-custom` | Use OpenAI provider to handle requests | Standard OpenAI API calls |
| `/gemini-cli-oauth` | Access via Gemini CLI OAuth | Break through Gemini free limits |
| `/openai-qwen-oauth` | Access via Qwen OAuth | Use Qwen Code Plus |
| `/openaiResponses-custom` | OpenAI Responses API | Structured dialogue scenarios |
**Usage Examples**:
```bash
# Configure in programming agents like Cline, Kilo
API_ENDPOINT=http://localhost:3000/claude-kiro-oauth
# Direct API call
curl http://localhost:3000/gemini-cli-oauth/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model":"gemini-2.0-flash-exp","messages":[...]}'
```
---
## 🌟 Special Usage & Advanced Tips
### 📁 Authorization File Storage Paths
* **🔌 Connect to Any OpenAI Client**: This is the fundamental feature of this project. Direct the API address of any OpenAI-compatible application (e.g., LobeChat, NextChat, VS Code extensions) to this service (`http://localhost:3000`) to seamlessly leverage all configured models.
Default storage locations for authorization credential files of each service:
* **🔍 Centralized Request Monitoring & Auditing**: Set `"PROMPT_LOG_MODE": "file"` in `config.json` to capture all requests and responses and save them to a local log file. This is vital for analyzing, debugging, and optimizing prompts, and even for constructing private datasets.
| Service | Default Path | Description |
|------|---------|------|
| **Gemini** | `~/.gemini/oauth_creds.json` | OAuth authentication credentials |
| **Kiro** | `~/.aws/sso/cache/kiro-auth-token.json` | Kiro authentication token |
| **Qwen** | `~/.qwen/oauth_creds.json` | Qwen OAuth credentials |
* **💡 Dynamic System Prompts**:
* By configuring `SYSTEM_PROMPT_FILE_PATH` and `SYSTEM_PROMPT_MODE` in `config.json`, you gain more flexible control over system prompt behavior.
* **Supported Modes**:
* `override`: Completely ignores the client's system prompt, enforcing the content from the file.
* `append`: Appends the file's content to the end of the client's system prompt, supplementing existing rules.
* This allows you to establish consistent base instructions for various clients while enabling individual applications to personalize extensions.
* **🛠️ Foundation for Secondary Development**:
* **Add New Models**: Simply create a new provider directory under `src`, implement the `ApiServiceAdapter` interface and corresponding strategies, and then register them in `adapter.js` and `common.js`.
* **Response Caching**: Implement caching logic for frequently repeated queries to reduce API calls and enhance response speed.
* **Custom Content Filtering**: Introduce keyword filtering or content review logic before sending or returning requests to ensure compliance.
* **🎯 Advanced Account Pool Configuration**:
* **Multi-Account Management**: Configure multiple accounts for each provider through the `provider_pools.json` file, enabling intelligent polling.
* **Failover**: When an account becomes unavailable, the system automatically switches to the next available account, ensuring service continuity.
* **Configuration Degradation**: Dynamically adjust configuration parameters based on account status to optimize resource usage efficiency.
* **Usage Example**: Refer to the `provider_pools.json` configuration file in the project to easily set up a multi-account environment.
> **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
---
@ -238,7 +261,7 @@ This project supports rich command-line parameter configuration, allowing flexib
|------|------|--------|------|
| `--host` | string | localhost | Server listening address |
| `--port` | number | 3000 | Server listening port |
| `--api-key` | string | 123456 | API key required for authentication |
| `--api-key` | string | 123456 | API key for authentication |
### 🤖 Model Provider Configuration Parameters
@ -250,49 +273,57 @@ This project supports rich command-line parameter configuration, allowing flexib
| Parameter | Type | Default Value | Description |
|------|------|--------|------|
| `--openai-api-key` | string | null | OpenAI API key (for openai-custom provider) |
| `--openai-base-url` | string | null | OpenAI API base URL (for openai-custom provider) |
| `--openai-api-key` | string | null | OpenAI API key (required when `model-provider` is `openai-custom`) |
| `--openai-base-url` | string | null | OpenAI API base URL (required when `model-provider` is `openai-custom`) |
### 🖥️ Claude Compatible Provider Parameters
| Parameter | Type | Default Value | Description |
|------|------|--------|------|
| `--claude-api-key` | string | null | Claude API key (for claude-custom provider) |
| `--claude-base-url` | string | null | Claude API base URL (for claude-custom provider) |
| `--claude-api-key` | string | null | Claude API key (required when `model-provider` is `claude-custom`) |
| `--claude-base-url` | string | null | Claude API base URL (required when `model-provider` is `claude-custom`) |
### 🔐 Gemini OAuth Authentication Parameters
| Parameter | Type | Default Value | Description |
|------|------|--------|------|
| `--gemini-oauth-creds-base64` | string | null | Base64 string of Gemini OAuth credentials |
| `--gemini-oauth-creds-file` | string | null | Gemini OAuth credentials JSON file path |
| `--project-id` | string | null | Google Cloud project ID (for gemini-cli provider) |
| `--gemini-oauth-creds-base64` | string | null | Base64 string of Gemini OAuth credentials (optional when `model-provider` is `gemini-cli-oauth`, choose one with `--gemini-oauth-creds-file`) |
| `--gemini-oauth-creds-file` | string | null | Gemini OAuth credentials JSON file path (optional when `model-provider` is `gemini-cli-oauth`, choose one with `--gemini-oauth-creds-base64`) |
| `--project-id` | string | null | Google Cloud project ID (required when `model-provider` is `gemini-cli-oauth`) |
### 🎮 Kiro OAuth Authentication Parameters
| Parameter | Type | Default Value | Description |
|------|------|--------|------|
| `--kiro-oauth-creds-base64` | string | null | Base64 string of Kiro OAuth credentials |
| `--kiro-oauth-creds-file` | string | null | Kiro OAuth credentials JSON file path |
| `--kiro-oauth-creds-base64` | string | null | Base64 string of Kiro OAuth credentials (optional when `model-provider` is `claude-kiro-oauth`, choose one with `--kiro-oauth-creds-file`) |
| `--kiro-oauth-creds-file` | string | null | Kiro OAuth credentials JSON file path (optional when `model-provider` is `claude-kiro-oauth`, choose one with `--kiro-oauth-creds-base64`) |
### 🐼 Qwen OAuth Authentication Parameters
| Parameter | Type | Default Value | Description |
|------|------|--------|------|
| `--qwen-oauth-creds-file` | string | null | Qwen OAuth credentials JSON file path |
| `--qwen-oauth-creds-file` | string | null | Qwen OAuth credentials JSON file path (required when `model-provider` is `openai-qwen-oauth`) |
### 🔄 OpenAI Responses API Parameters
| Parameter | Type | Default Value | Description |
|------|------|--------|------|
| `--model-provider` | string | openaiResponses-custom | Model provider, set to `openaiResponses-custom` when using OpenAI Responses API |
| `--openai-api-key` | string | null | OpenAI API key (required when `model-provider` is `openaiResponses-custom`) |
| `--openai-base-url` | string | null | OpenAI API base URL (required when `model-provider` is `openaiResponses-custom`) |
### 📝 System Prompt Configuration Parameters
| Parameter | Type | Default Value | Description |
|------|------|--------|------|
| `--system-prompt-file` | string | input_system_prompt.txt | System prompt file path |
| `--system-prompt-mode` | string | overwrite | System prompt mode, optional values: overwrite, append |
| `--system-prompt-mode` | string | overwrite | System prompt mode, optional values: overwrite (override), append (append) |
### 📊 Log Configuration Parameters
| Parameter | Type | Default Value | Description |
|------|------|--------|------|
| `--log-prompts` | string | none | Prompt log mode, optional values: console, file, none |
| `--log-prompts` | string | none | Prompt log mode, optional values: console (console), file (file), none (none) |
| `--prompt-log-base-name` | string | prompt_log | Prompt log file base name |
### 🔄 Retry Mechanism Parameters
@ -330,6 +361,9 @@ node src/api-server.js --model-provider openai-custom --openai-api-key sk-xxx --
# Use Claude provider
node src/api-server.js --model-provider claude-custom --claude-api-key sk-ant-xxx --claude-base-url https://api.anthropic.com
# Use OpenAI Responses API provider
node src/api-server.js --model-provider openaiResponses-custom --openai-api-key sk-xxx --openai-base-url https://api.openai.com/v1
# Use Gemini provider (Base64 credentials)
node src/api-server.js --model-provider gemini-cli-oauth --gemini-oauth-creds-base64 eyJ0eXBlIjoi... --project-id your-project-id

View file

@ -14,47 +14,65 @@
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
[![Node.js](https://img.shields.io/badge/Node.js-≥20.0.0-green.svg)](https://nodejs.org/)
[![docker](https://img.shields.io/badge/docker-≥20.0.0-green.svg)](https://aiproxy.justlikemaki.vip/zh/docs/installation/docker-deployment.html)
[![Docker](https://img.shields.io/badge/docker-≥20.0.0-blue.svg)](https://aiproxy.justlikemaki.vip/ja/docs/installation/docker-deployment.html)
[**中文**](./README.md) | [**English**](./README-EN.md) | [**日本語**](./README-JA.md) | [**詳細ドキュメント**](https://aiproxy.justlikemaki.vip/)
[**中文**](./README.md) | [**English**](./README-EN.md) | [**日本語**](./README-JA.md) | [**📚 完全ドキュメント**](https://aiproxy.justlikemaki.vip/ja/)
</div>
`AIClient2API`開発者向けに作られた多機能で軽量なAPIプロキシです。大量の無料APIリクエスト枠を提供し、Gemini、Qwen Code、Claudeなどの主要な大規模言語モデルを完全にサポートします。Node.js HTTPサーバーを通じて、複数のバックエンドAPIを標準的なOpenAI形式のインターフェースに統一的に変換します。本プロジェクトは最新のモジュラーアーキテクチャを採用し、ストラテジーパターンとアダプターパターンをサポートし、完全なテストカバレッジとヘルスチェック機構を備えています。`npm install` 後すぐに使用できます。設定ファイルでモデルプロバイダーを簡単に切り替えるだけで、OpenAI互換のクライアントやアプリケーションが同一のAPIアドレスを通じて、異なる大規模言語モデルの機能をシームレスに使用でき、異なるサービスのために複数の設定を維持し、インターフェース非互換問題を処理する煩わしさから完全に解放されます。
`AIClient2API`クライアント制限を突破するAPIプロキシサービスで、元々クライアント内でのみ使用可能な無料大規模モデルGemini CLI、Qwen Code Plus、Kiro Claudeなどを、あらゆるアプリケーションから呼び出せる標準OpenAI互換インターフェースに変換します。Node.jsをベースに構築され、OpenAI、Claude、Geminiの3大プロトコル間のインテリジェント変換をサポートし、Cherry-Studio、NextChat、Clineなどのツールで、Claude Sonnet 4.5、Gemini 2.5 Flash、Qwen3 Coder Plusなどの高度なモデルを大規模に無料で使用できるようにします。プロジェクトはストラテジーパターンとアダプターパターンに基づくモジュラーアーキテクチャを採用し、アカウントプール管理、インテリジェントポーリング、自動フェイルオーバー、ヘルスチェック機構を内蔵し、99.9%のサービス可用性を保証します。
> [!NOTE]
> Ruan Yifeng先生による[週刊359号](https://www.ruanyifeng.com/blog/2025/08/weekly-issue-359.html)での推薦に感謝します。
> **🎉 重要なマイルストーン**
>
> 8.29 アカウントプールモードを追加。すべてのプロバイダーで複数アカウントの設定をサポート。ラウンドロビン、フェイルオーバークライアント再試行必要、設定ダウングレードを内蔵。configでPROVIDER_POOLS_FILE_PATH設定が必要。詳細は設定ファイルprovider_pools.json参照
> - Ruan Yifeng先生による[週刊359号](https://www.ruanyifeng.com/blog/2025/08/weekly-issue-359.html)での推薦に感謝します
>
> 9.1 Qwen Code CLIサポートを密かに追加、qwen3-coder-plusモデルが使用可能
>
> 10.18 Kiroはオープン登録、新規アカウントに500クレジット付与、Claude Sonnet4.5に対応
> **📅 バージョン更新ログ**
>
> - **2025.10.18** - Kiroオープン登録、新規アカウントに500クレジット付与、Claude Sonnet 4.5を完全サポート
> - **2025.09.01** - Qwen Code CLIを統合、`qwen3-coder-plus`モデルサポートを追加
> - **2025.08.29** - アカウントプール管理機能をリリース、マルチアカウントポーリング、インテリジェントフェイルオーバー、自動ダウングレード戦略をサポート
> - 設定方法config.jsonに`PROVIDER_POOLS_FILE_PATH`パラメータを追加
> - 参考設定:[provider_pools.json](./provider_pools.json.example)
---
## 💡 コア機能
## 💡 コアアドバンテージ
* ✅ **マルチモデル統一アクセス**一つのインターフェースで、Gemini、OpenAI、Claude、Kimi K2、GLM-4.5、Qwen Codeなど複数の最新モデルに対応。シンプルな起動パラメータやリクエストヘッダーで、異なるモデルプロバイダー間を自由に切り替え可能。
* ✅ **公式制限の突破**Gemini CLIのOAuth認証方式をサポートすることで、公式無料APIのレート制限と割り当て制限を効果的に回避し、より高いリクエスト枠と使用頻度を享受。
* ✅ **クライアント制限の突破**Kiro APIモードでClaude Sonnet 4.5モデルの無料使用をサポート。
* ✅ **OpenAIとのシームレスな互換性**OpenAI APIと完全に互換性のあるインターフェースを提供し、既存のツールチェーンとクライアントLobeChat、NextChatなどがゼロコストですべてのサポートモデルに接続可能。
* ✅ **アカウントプールのインテリジェント管理**:マルチアカウントのラウンドロビン、フェイルオーバー、設定ダウングレードをサポートし、サービスの高可用性を確保し、単一アカウントの制限問題を効果的に回避。
* ✅ **強化された制御性**:強力なログ機能により、すべてのリクエストのプロンプトをキャプチャして記録でき、監査、デバッグ、プライベートデータセット構築に便利。
* ✅ **極めて拡張しやすい**:新しいモジュラーとストラテジーパターン設計により、新しいモデルプロバイダーの追加がかつてないほど簡単。
* ✅ **完全なテストカバレッジ**包括的な統合テストと単体テストを提供し、各APIエンドポイントと機能の安定性と信頼性を確保。
* ✅ **Dockerサポート**完全なDockerコンテナ化サポートを提供し、迅速なデプロイと環境の分離をサポート。
### 🎯 統一アクセス、ワンストップ管理
* **マルチモデル統一インターフェース**標準OpenAI互換プロトコルを通じて、一度の設定でGemini、Claude、GPT、Qwen Code、Kimi K2、GLM-4.6などの主流大規模モデルにアクセス
* **柔軟な切り替えメカニズム**起動パラメータ、Pathルーティング、環境変数の3つの方法で動的にモデルを切り替え、異なるシナリオのニーズに対応
* **ゼロコスト移行**OpenAI API仕様と完全互換、Cherry-Studio、NextChat、Clineなどのツールを変更なしで使用可能
* **マルチプロトコルインテリジェント変換**OpenAI、Claude、Geminiの3大プロトコル間のインテリジェント変換をサポートし、クロスプロトコルモデル呼び出しを実現
* OpenAIプロトコルでClaudeモデルを呼び出す`claude-custom`または`claude-kiro-oauth`プロバイダーを使用
* OpenAIプロトコルでGeminiモデルを呼び出す`gemini-cli-oauth`プロバイダーを使用
* ClaudeプロトコルでGeminiモデルを呼び出す`gemini-cli-oauth`プロバイダーを使用
* ClaudeプロトコルでOpenAIモデルを呼び出す`openai-custom`または`openai-qwen-oauth`プロバイダーを使用
### 🚀 制限を突破、効率を向上
* **公式制限の回避**OAuth認証メカニズムを利用して、Geminiなどの無料APIのレート制限と割り当て制限を効果的に突破
* **無料高度モデル**Kiro APIモードでClaude Sonnet 4.5を無料使用、Qwen OAuthモードでQwen3 Coder Plusを使用し、使用コストを削減
* **インテリジェントアカウントプールスケジューリング**マルチアカウントポーリング、自動フェイルオーバー、設定ダウングレードをサポートし、99.9%のサービス可用性を保証
### 🛡️ 安全で制御可能、データ透明
* **フルチェーンログ記録**:すべてのリクエストとレスポンスデータをキャプチャし、監査とデバッグをサポート
* **プライベートデータセット構築**:ログデータに基づいて専用トレーニングデータセットを迅速に構築
* **システムプロンプト管理**オーバーライドと追加の2つのモードをサポートし、統一された基本指示と個別拡張の完璧な組み合わせを実現
### 🔧 開発者フレンドリー、拡張が容易
* **モジュラーアーキテクチャ**ストラテジーパターンとアダプターパターンに基づき、新しいモデルプロバイダーの追加はわずか3ステップ
* **完全なテストカバレッジ**統合テストと単体テストのカバレッジ90%+、コード品質を保証
* **コンテナ化デプロイ**Dockerサポートを提供、ワンクリックデプロイ、クロスプラットフォーム実行
* **MCPプロトコルサポート**Model Context Protocolと完全互換、機能を簡単に拡張
---
## 📑 クイックナビゲーション
- [🐳 Docker デプロイ](https://aiproxy.justlikemaki.vip/zh/docs/installation/docker-deployment.html)
- [🐳 Docker デプロイ](https://aiproxy.justlikemaki.vip/ja/docs/installation/docker-deployment.html)
- [🎨 モデルプロトコルとプロバイダー関係図](#-モデルプロトコルとプロバイダー関係図)
- [🔧 使用方法](#-使用方法)
- [💻 プロキシ設定](#-プロキシ設定)
- [🌟 特殊な使用法と上級テクニック](#-特殊な使用法と上級テクニック)
- [🚀 プロジェクト起動パラメータ](#-プロジェクト起動パラメータ)
- [📄 オープンソースライセンス](#-オープンソースライセンス)
- [🙏 謝辞](#-謝辞)
@ -64,12 +82,13 @@
## 🎨 モデルプロトコルとプロバイダー関係図
本プロジェクトは異なるプロトコルを通じて複数のモデルプロバイダーをサポートします。以下はそれらの関係の概要です:
- OpenAIプロトコル (P_OPENAI): すべてのMODEL_PROVIDERをサポート。openai-custom、gemini-cli-oauth、claude-custom、
claude-kiro-oauth、openai-qwen-oauthを含む。
- Claudeプロトコル (P_CLAUDE): claude-custom、claude-kiro-oauth、gemini-cli-oauth、openai-custom、openai-qwen-oauthをサポート。
- Geminiプロトコル (P_GEMINI): gemini-cli-oauthをサポート。
* **OpenAIプロトコル (P_OPENAI)**`openai-custom`、`gemini-cli-oauth`、`claude-custom`、`claude-kiro-oauth`、`openai-qwen-oauth`モデルプロバイダーによって実装。
* **Claudeプロトコル (P_CLAUDE)**`claude-custom`、`claude-kiro-oauth`、`gemini-cli-oauth`、`openai-custom`、`openai-qwen-oauth`モデルプロバイダーによって実装。
* **Geminiプロトコル (P_GEMINI)**`gemini-cli-oauth`モデルプロバイダーによって実装。
詳細な関係図:
```mermaid
@ -112,124 +131,123 @@ claude-kiro-oauth、openai-qwen-oauthを含む。
## 🔧 使用方法
* **MCPサポート**: オリジナルのGemini CLIの内蔵コマンド機能は使用できませんが、本プロジェクトはMCP (Model Context Protocol)を完璧にサポートし、MCPをサポートするクライアントと組み合わせることで、より強力な機能拡張が可能です。
* **マルチモーダル機能**: 画像、ドキュメントなどのマルチモーダル入力をサポートし、よりリッチなインタラクティブ体験を提供。
* **最新モデルサポート**: 最新の **Kimi K2**、**GLM-4.5**、**Qwen Code** モデルをサポート。`config.json` で対応するOpenAIまたはClaude互換インターフェースを設定するだけで使用可能。
* **Qwen Codeサポート**: Qwen Code使用時は自動的にブラウザで認証ページが開き、認証完了後に `~/.qwen` ディレクトリに `oauth_creds.json` ファイルが生成されます。公式デフォルトパラメータ temperature=0、top_p=1 を使用してください。
* **Kiro API**: Kiro API使用には[kiroクライアントをダウンロード](https://aibook.ren/archives/kiro-install)して認証ログインを完了し、kiro-auth-token.jsonを生成する必要があります。**最適な体験のためClaude Codeとの併用を推奨**。注意Kiroサービスポリシーが調整されました。具体的な使用制限は公式発表をご確認ください。
* **Claude Codeで異なるプロバイダーを使用**: Pathルーティングまたは環境変数を通じて、Claude関連のAPI呼び出しで異なるプロバイダーを使用できます
* `http://localhost:3000/claude-custom` - 設定ファイルで定義されたClaude APIプロバイダーを使用
* `http://localhost:3000/claude-kiro-oauth` - Kiro OAuth認証方式でClaude APIにアクセス
* `http://localhost:3000/openai-custom` - OpenAIカスタムプロバイダーでClaudeリクエストを処理
* `http://localhost:3000/gemini-cli-oauth` - Gemini CLI OAuthプロバイダーでClaudeリクエストを処理
* `http://localhost:3000/openai-qwen-oauth` - Qwen OAuthプロバイダーでClaudeリクエストを処理
* 各プロバイダーで異なるAPIキー、ベースURL、その他のパラメータを設定でき、柔軟なプロバイダー切り替えを実現
### 📋 コア機能
これらのPathルートは直接のAPI呼び出しだけでなく、Cline、Kiloなどのプログラミングエージェントでも使用でき、異なるパスを指定することで対応するモデルを呼び出せます。例えば、プログラミングエージェントでAPIエンドポイントを設定する際、`http://localhost:3000/claude-kiro-oauth` を使用してKiro OAuth認証されたClaudeモデルを呼び出したり、`http://localhost:3000/gemini-cli-oauth` を使用してGeminiモデルを呼び出したりできます。
#### MCPプロトコルサポート
本プロジェクトは**Model Context Protocol (MCP)**と完全互換で、MCPをサポートするクライアントとシームレスに統合し、強力な機能拡張を実現します。
Pathルートによるプロバイダー切り替えの他に、環境変数を設定してClaudeパラメータを設定することもできます。以下の環境変数で設定可能
#### マルチモーダル入力機能
画像、ドキュメントなど様々なタイプの入力をサポートし、よりリッチなインタラクティブ体験とより強力なアプリケーションシナリオを提供します。
* `ANTHROPIC_BASE_URL`: Claude APIのベースURLパスを設定
* `ANTHROPIC_AUTH_TOKEN`: Claudeサービスの認証キーを設定
* `ANTHROPIC_MODEL`: 使用するClaudeモデルを設定
#### 異なるシステムでの環境変数設定方法
`http://localhost:3000/claude-custom` パスを使用する場合、以下の方法で環境変数を設定できます:
##### Linux / macOS
```bash
export ANTHROPIC_BASE_URL="http://localhost:3000/claude-custom"
export ANTHROPIC_AUTH_TOKEN="your-auth-token-here"
export ANTHROPIC_MODEL="your-model-name"
```
##### Windows (CMD)
```cmd
set ANTHROPIC_BASE_URL=http://localhost:3000/claude-custom
set ANTHROPIC_AUTH_TOKEN=your-auth-token-here
set ANTHROPIC_MODEL=your-model-name
```
##### Windows (PowerShell)
```powershell
$env:ANTHROPIC_BASE_URL="http://localhost:3000/claude-custom"
$env:ANTHROPIC_AUTH_TOKEN="your-auth-token-here"
$env:ANTHROPIC_MODEL="your-model-name"
```
### 認証ファイルのデフォルトパス
各サービスの認証ファイルのデフォルト保存パス:
* **Gemini**: `~/.gemini/oauth_creds.json`
* **Kiro**: `~/.aws/sso/cache/kiro-auth-token.json`
* **Qwen**: `~/.qwen/oauth_creds.json`
ここで `~` はユーザーホームディレクトリを表します。カスタムパスが必要な場合は、設定ファイルまたは環境変数で設定できます。
#### 最新モデルサポート
以下の最新大規模モデルをシームレスにサポート、[`config.json`](./config.json)で対応するOpenAIまたはClaude互換インターフェースを設定するだけで使用可能
* **Kimi K2** - 月之暗面の最新フラッグシップモデル
* **GLM-4.5** - 智譜AIの最新バージョン
* **Qwen Code** - アリババ通義千問のコード専用モデル
---
### 🔐 認証設定ガイド
## 💻 プロキシ設定
#### Gemini CLI OAuth設定
1. **OAuth認証情報の取得**[Google Cloud Console](https://console.cloud.google.com/)にアクセスしてプロジェクトを作成し、Gemini APIを有効化
2. **初回認証**Geminiサービス使用後、コマンドラインにGoogle認証ページが表示されるので、ページをブラウザにコピーして認証し、コマンドラインに戻る
3. **認証情報の保存**:認証成功後、`oauth_creds.json`ファイルが自動生成され、`~/.gemini`ディレクトリに保存される
4. **プロジェクト設定**有効なGoogle CloudプロジェクトIDを提供する必要があり、起動パラメータ`--project-id`で指定可能
> **ヒント**: Google/OpenAI/Claude/Kiroサービスに直接アクセスできない環境で使用する場合は、まずターミナルにHTTPプロキシを設定してください。HTTPSプロキシは設定しないでください。
#### Qwen Code OAuth設定
1. **初回認証**:サービス起動後、システムが自動的にブラウザで認証ページを開く
2. **認証情報の保存**:認証成功後、`oauth_creds.json`ファイルが自動生成され、`~/.qwen`ディレクトリに保存される
3. **推奨パラメータ**:最良の結果を得るために公式デフォルトパラメータを使用
```json
{
"temperature": 0,
"top_p": 1
}
```
### 異なるターミナル環境でのHTTPプロキシ設定コマンド
#### Kiro API設定
1. **環境準備**[Kiroクライアントをダウンロードしてインストール](https://aibook.ren/archives/kiro-install)
2. **認証完了**:クライアントでアカウントにログインし、`kiro-auth-token.json`認証情報ファイルを生成
3. **ベストプラクティス****Claude Code**との併用を推奨、最適な体験を得られる
4. **重要なお知らせ**Kiroサービス使用ポリシーが更新されました、最新の使用制限と条件については公式ウェブサイトをご確認ください
`AIClient2API` が外部AIサービスGoogle、OpenAI、Claude、Kiroなどに正常にアクセスできるようにするため、ターミナル環境でHTTPプロキシを設定する必要がある場合があります。以下は異なるオペレーティングシステム向けのプロキシ設定コマンドです
#### OpenAI Responses API
* **適用シナリオ**Codexなど、OpenAI Responses APIを使用した構造化対話が必要なシナリオに適用
* **設定方法**
* 方法1[`config.json`](./config.json)で`MODEL_PROVIDER`を`openaiResponses-custom`に設定
* 方法2起動パラメータ`--model-provider openaiResponses-custom`を使用
* 方法3パスルーティング`/openaiResponses-custom`を使用
* **必須パラメータ**有効なAPIキーとベースURLを提供
---
### 🔄 モデルプロバイダー切り替え
本プロジェクトは2つの柔軟なモデル切り替え方法を提供し、異なる使用シナリオのニーズに対応します。
#### 方法1起動パラメータ切り替え
コマンドラインパラメータでデフォルトのモデルプロバイダーを指定:
#### Linux / macOS
```bash
export HTTP_PROXY="http://your_proxy_address:port"
# プロキシに認証が必要な場合
# export HTTP_PROXY="http://username:password@your_proxy_address:port"
```
これらの設定を永続化するには、シェル設定ファイル(例:`~/.bashrc`、`~/.zshrc`、`~/.profile`)に追加してください。
# Geminiプロバイダーを使用
node src/api-server.js --model-provider gemini-cli-oauth --project-id your-project-id
#### Windows (CMD)
```cmd
set HTTP_PROXY=http://your_proxy_address:port
:: プロキシに認証が必要な場合
:: set HTTP_PROXY=http://username:password@your_proxy_address:port
```
これらの設定は現在のCMDセッションでのみ有効です。永続的に設定するには、システム環境変数で設定してください。
# Claude Kiroプロバイダーを使用
node src/api-server.js --model-provider claude-kiro-oauth
#### Windows (PowerShell)
```powershell
$env:HTTP_PROXY="http://your_proxy_address:port"
# プロキシに認証が必要な場合
# $env:HTTP_PROXY="http://username:password@your_proxy_address:port"
# Qwenプロバイダーを使用
node src/api-server.js --model-provider openai-qwen-oauth
```
これらの設定は現在のPowerShellセッションでのみ有効です。永続的に設定するには、PowerShell設定ファイル (`$PROFILE`) に追加するか、システム環境変数で設定してください。
**必ず `your_proxy_address``port` を実際のプロキシアドレスとポートに置き換えてください。**
**利用可能なモデルプロバイダー識別子**
- `openai-custom` - 標準OpenAI API
- `claude-custom` - 公式Claude API
- `gemini-cli-oauth` - Gemini CLI OAuth
- `claude-kiro-oauth` - Kiro Claude OAuth
- `openai-qwen-oauth` - Qwen Code OAuth
- `openaiResponses-custom` - OpenAI Responses API
#### 方法2Pathルーティング切り替え推奨
APIリクエストパスでプロバイダー識別子を指定して即座に切り替え
| ルートパス | 説明 | 使用ケース |
|---------|------|---------|
| `/claude-custom` | 設定ファイルのClaude APIを使用 | 公式Claude API呼び出し |
| `/claude-kiro-oauth` | Kiro OAuth経由でClaudeにアクセス | Claude Sonnet 4.5の無料使用 |
| `/openai-custom` | OpenAIプロバイダーでリクエストを処理 | 標準OpenAI API呼び出し |
| `/gemini-cli-oauth` | Gemini CLI OAuth経由でアクセス | Gemini無料制限の突破 |
| `/openai-qwen-oauth` | Qwen OAuth経由でアクセス | Qwen Code Plusの使用 |
| `/openaiResponses-custom` | OpenAI Responses API | 構造化対話シナリオ |
**使用例**
```bash
# Cline、Kiloなどのプログラミングエージェントで設定
API_ENDPOINT=http://localhost:3000/claude-kiro-oauth
# 直接API呼び出し
curl http://localhost:3000/gemini-cli-oauth/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model":"gemini-2.0-flash-exp","messages":[...]}'
```
---
## 🌟 特殊な使用法と上級テクニック
### 📁 認証ファイル保存パス
* **🔌 任意のOpenAIクライアントとの接続**: 本プロジェクトの基本機能です。OpenAIをサポートする任意のアプリケーションLobeChat、NextChat、VS CodeプラグインなどのAPIアドレスを本サービス (`http://localhost:3000`) に向けることで、設定済みのすべてのモデルをシームレスに使用できます。
各サービスの認証情報ファイルのデフォルト保存場所:
* **🔍 一元的なリクエスト監視と監査**: `config.json``"PROMPT_LOG_MODE": "file"` を設定することで、すべてのリクエストとレスポンスをキャプチャし、ローカルログファイルに保存します。これはプロンプトの分析、デバッグ、最適化、さらにはプライベートデータセットの構築にとって重要です。
| サービス | デフォルトパス | 説明 |
|------|---------|------|
| **Gemini** | `~/.gemini/oauth_creds.json` | OAuth認証情報 |
| **Kiro** | `~/.aws/sso/cache/kiro-auth-token.json` | Kiro認証トークン |
| **Qwen** | `~/.qwen/oauth_creds.json` | Qwen OAuth認証情報 |
* **💡 動的システムプロンプト**:
* `config.json``SYSTEM_PROMPT_FILE_PATH``SYSTEM_PROMPT_MODE` を設定することで、システムプロンプトの動作をより柔軟に制御できます。
* **サポートモード**:
* `override`: クライアントのシステムプロンプトを完全に無視し、ファイルの内容を強制使用。
* `append`: クライアントシステムプロンプトの末尾にファイルの内容を追加し、ルールを補完。
* これにより、異なるクライアントに統一された基本指示を設定しながら、個々のアプリケーションで個性的な拡張を許可できます。
* **🛠️ 二次開発の基盤として**:
* **新モデルの追加**: `src` ディレクトリに新しいプロバイダーディレクトリを作成し、`ApiServiceAdapter` インターフェースと対応するストラテジーを実装し、`adapter.js` と `common.js` に登録するだけです。
* **レスポンスキャッシュ**: 高頻度の繰り返し質問にキャッシュロジックを追加し、API呼び出しを削減し、レスポンス速度を向上。
* **カスタムコンテンツフィルタリング**: リクエスト送信前または返却前にキーワードフィルタリングやコンテンツ審査ロジックを追加し、コンプライアンス要件を満たす。
* **🎯 アカウントプールの高度な設定**:
* **マルチアカウント管理**: `provider_pools.json` ファイルを設定することで、各プロバイダーに複数のアカウントを設定し、インテリジェントなラウンドロビンを実現。
* **フェイルオーバー**: あるアカウントが無効になった場合、システムは自動的に次の利用可能なアカウントに切り替え、サービスの継続性を確保。
* **設定ダウングレード**: アカウント状態に基づいて設定パラメータを動的に調整し、リソース使用効率を最適化。
* **使用例**: プロジェクトの `provider_pools.json` 設定ファイルを参照し、マルチアカウント環境を簡単に設定。
> **説明**`~`はユーザーホームディレクトリを表しますWindows: `C:\Users\ユーザー名`、Linux/macOS: `/home/ユーザー名`または`/Users/ユーザー名`
>
> **カスタムパス**:設定ファイルの関連パラメータまたは環境変数でカスタム保存場所を指定可能
---
@ -243,7 +261,7 @@ $env:HTTP_PROXY="http://your_proxy_address:port"
|------|------|--------|------|
| `--host` | string | localhost | サーバーリッスンアドレス |
| `--port` | number | 3000 | サーバーリッスンポート |
| `--api-key` | string | 123456 | 認証に必要なAPIキー |
| `--api-key` | string | 123456 | 認証APIキー |
### 🤖 モデルプロバイダー設定パラメータ
@ -255,36 +273,44 @@ $env:HTTP_PROXY="http://your_proxy_address:port"
| パラメータ | タイプ | デフォルト値 | 説明 |
|------|------|--------|------|
| `--openai-api-key` | string | null | OpenAI APIキー (openai-customプロバイダー用) |
| `--openai-base-url` | string | null | OpenAI APIベースURL (openai-customプロバイダー用) |
| `--openai-api-key` | string | null | OpenAI APIキー`model-provider`が`openai-custom`の場合必須) |
| `--openai-base-url` | string | null | OpenAI APIベースURL`model-provider`が`openai-custom`の場合必須) |
### 🖥️ Claude互換プロバイダーパラメータ
| パラメータ | タイプ | デフォルト値 | 説明 |
|------|------|--------|------|
| `--claude-api-key` | string | null | Claude APIキー (claude-customプロバイダー用) |
| `--claude-base-url` | string | null | Claude APIベースURL (claude-customプロバイダー用) |
| `--claude-api-key` | string | null | Claude APIキー`model-provider`が`claude-custom`の場合必須) |
| `--claude-base-url` | string | null | Claude APIベースURL`model-provider`が`claude-custom`の場合必須) |
### 🔐 Gemini OAuth認証パラメータ
| パラメータ | タイプ | デフォルト値 | 説明 |
|------|------|--------|------|
| `--gemini-oauth-creds-base64` | string | null | Gemini OAuth認証情報のBase64文字列 |
| `--gemini-oauth-creds-file` | string | null | Gemini OAuth認証情報JSONファイルパス |
| `--project-id` | string | null | Google CloudプロジェクトID (gemini-cliプロバイダー用) |
| `--gemini-oauth-creds-base64` | string | null | Gemini OAuth認証情報のBase64文字列`model-provider`が`gemini-cli-oauth`の場合オプション、`--gemini-oauth-creds-file`と二者択一) |
| `--gemini-oauth-creds-file` | string | null | Gemini OAuth認証情報JSONファイルパス`model-provider`が`gemini-cli-oauth`の場合オプション、`--gemini-oauth-creds-base64`と二者択一) |
| `--project-id` | string | null | Google CloudプロジェクトID`model-provider`が`gemini-cli-oauth`の場合必須) |
### 🎮 Kiro OAuth認証パラメータ
| パラメータ | タイプ | デフォルト値 | 説明 |
|------|------|--------|------|
| `--kiro-oauth-creds-base64` | string | null | Kiro OAuth認証情報のBase64文字列 |
| `--kiro-oauth-creds-file` | string | null | Kiro OAuth認証情報JSONファイルパス |
| `--kiro-oauth-creds-base64` | string | null | Kiro OAuth認証情報のBase64文字列`model-provider`が`claude-kiro-oauth`の場合オプション、`--kiro-oauth-creds-file`と二者択一) |
| `--kiro-oauth-creds-file` | string | null | Kiro OAuth認証情報JSONファイルパス`model-provider`が`claude-kiro-oauth`の場合オプション、`--kiro-oauth-creds-base64`と二者択一) |
### 🐼 Qwen OAuth認証パラメータ
| パラメータ | タイプ | デフォルト値 | 説明 |
|------|------|--------|------|
| `--qwen-oauth-creds-file` | string | null | Qwen OAuth認証情報JSONファイルパス |
| `--qwen-oauth-creds-file` | string | null | Qwen OAuth認証情報JSONファイルパス`model-provider`が`openai-qwen-oauth`の場合必須) |
### 🔄 OpenAI Responses APIパラメータ
| パラメータ | タイプ | デフォルト値 | 説明 |
|------|------|--------|------|
| `--model-provider` | string | openaiResponses-custom | モデルプロバイダー、OpenAI Responses API使用時は`openaiResponses-custom`に設定 |
| `--openai-api-key` | string | null | OpenAI APIキー`model-provider`が`openaiResponses-custom`の場合必須) |
| `--openai-base-url` | string | null | OpenAI APIベースURL`model-provider`が`openaiResponses-custom`の場合必須) |
### 📝 システムプロンプト設定パラメータ
@ -335,6 +361,9 @@ node src/api-server.js --model-provider openai-custom --openai-api-key sk-xxx --
# Claudeプロバイダーを使用
node src/api-server.js --model-provider claude-custom --claude-api-key sk-ant-xxx --claude-base-url https://api.anthropic.com
# OpenAI Responses APIプロバイダーを使用
node src/api-server.js --model-provider openaiResponses-custom --openai-api-key sk-xxx --openai-base-url https://api.openai.com/v1
# Geminiプロバイダーを使用Base64認証情報
node src/api-server.js --model-provider gemini-cli-oauth --gemini-oauth-creds-base64 eyJ0eXBlIjoi... --project-id your-project-id

257
README.md
View file

@ -14,37 +14,57 @@
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
[![Node.js](https://img.shields.io/badge/Node.js-≥20.0.0-green.svg)](https://nodejs.org/)
[![docker](https://img.shields.io/badge/docker-≥20.0.0-green.svg)](https://aiproxy.justlikemaki.vip/zh/docs/installation/docker-deployment.html)
[![Docker](https://img.shields.io/badge/docker-≥20.0.0-blue.svg)](https://aiproxy.justlikemaki.vip/zh/docs/installation/docker-deployment.html)
[**中文**](./README.md) | [**English**](./README-EN.md) | [**日本語**](./README-JA.md) | [**更详细文档**](https://aiproxy.justlikemaki.vip/)
[**中文**](./README.md) | [**English**](./README-EN.md) | [**日本語**](./README-JA.md) | [**📚 完整文档**](https://aiproxy.justlikemaki.vip/)
</div>
`AIClient2API` 是一个多功能、轻量化的 API 代理,旨在将多种大模型客户端(如 Gemini CLI, Qwen Code Plus, Kiro Claude 等)模拟为本地 OpenAI 兼容接口。它通过一个 Node.js HTTP 服务器,将不同模型的后端 API 统一转换为标准的 OpenAI 格式,让任何兼容 OpenAI 的客户端或应用,通过一个 API 地址,无缝使用多种大模型能力,从而摆脱多套配置和接口不兼容的烦恼。项目支持模块化架构、策略模式和适配器模式,具备完整的测试覆盖和健康检查,开箱即用
`AIClient2API` 是一个突破客户端限制的 API 代理服务,将 Gemini CLI、Qwen Code Plus、Kiro Claude 等原本仅限客户端使用的免费大模型,转换为可供任何应用调用的标准 OpenAI 兼容接口。基于 Node.js 构建,支持 OpenAI、Claude、Gemini 三大协议的智能互转,让 Cherry-Studio、NextChat、Cline 等工具能够免费大量使用 Claude Sonnet 4.5、Gemini 2.5 Flash、Qwen3 Coder Plus 等高级模型。项目采用策略模式和适配器模式的模块化架构,内置账号池管理、智能轮询、自动故障转移和健康检查机制,确保 99.9% 的服务可用性
> [!NOTE]
> 感谢阮一峰老师在[周刊359期](https://www.ruanyifeng.com/blog/2025/08/weekly-issue-359.html)的推荐。
> **🎉 重要里程碑**
>
> 8.29 新增账号池模式可支持所有provider配置多个账号自带轮询故障转移需要客户端重试和配置降级。需要在 config 新增配置 PROVIDER_POOLS_FILE_PATH 详见配置文件provider_pools.json
> - 感谢阮一峰老师在 [周刊 359 期](https://www.ruanyifeng.com/blog/2025/08/weekly-issue-359.html) 的推荐
>
> 9.1 偷摸的新增 Qwen Code CLI 支持,可使用 qwen3-coder-plus 模型
>
> 10.18 Kiro开放注册新号送500额度已支持Claude Sonnet4.5
> **📅 版本更新日志**
>
> - **2025.10.18** - Kiro 开放注册,新用户赠送 500 额度,已完整支持 Claude Sonnet 4.5
> - **2025.09.01** - 集成 Qwen Code CLI新增 `qwen3-coder-plus` 模型支持
> - **2025.08.29** - 发布账号池管理功能,支持多账号轮询、智能故障转移和自动降级策略
> - 配置方式:在 config.json 中添加 `PROVIDER_POOLS_FILE_PATH` 参数
> - 参考配置:[provider_pools.json](./provider_pools.json.example)
---
## 💡 核心优势
* ✅ **多模型统一接入**:通过统一的 OpenAI 兼容接口,轻松接入 Gemini、OpenAI、Claude、Kimi K2、GLM-4.5、Qwen Code 等多种主流大模型,并通过启动参数或请求头自由切换。
* ✅ **突破官方限制**:利用 Gemini CLI 的 OAuth 授权,有效规避官方免费 API 的速率和配额限制,提升请求额度和使用频率。
* ✅ **免费使用 Claude Sonnet 4.5**:在 Kiro API 模式下,支持免费使用 Claude Sonnet 4.5 模型。
* ✅ **无缝兼容 OpenAI**:提供与 OpenAI API 完全兼容的接口,使 LobeChat, NextChat 等现有工具链和客户端能零成本接入所有支持模型。
* ✅ **账号池智能管理**:支持多账号轮询、故障转移和配置降级,确保服务高可用性,有效应对单一账号限制。
* ✅ **增强的可控性**强大的日志功能可捕获并记录所有请求的提示词Prompts便于审计、调试、优化模型行为和构建私有数据集。
* ✅ **极易扩展**:采用模块化和策略模式设计,新增模型服务商变得前所未有的简单。
* ✅ **完整测试覆盖**:全面的集成和单元测试,确保各个 API 端点和功能的稳定可靠。
* ✅ **Docker支持**:提供完整的 Docker 容器化支持,实现快速部署和环境隔离。
### 🎯 统一接入,一站式管理
* **多模型统一接口**:通过标准 OpenAI 兼容协议,一次配置即可接入 Gemini、Claude、GPT、Qwen Code、Kimi K2、GLM-4.6 等主流大模型
* **灵活切换机制**支持通过启动参数、Path 路由、环境变量三种方式动态切换模型,满足不同场景需求
* **零成本迁移**:完全兼容 OpenAI API 规范Cherry-Studio、NextChat、Cline 等工具无需修改即可使用
* **多协议智能转换**:支持 OpenAI、Claude、Gemini 三大协议间的智能转换,实现跨协议模型调用
* 使用 OpenAI 协议调用 Claude 模型:可使用 `claude-custom``claude-kiro-oauth` 提供商
* 使用 OpenAI 协议调用 Gemini 模型:可使用 `gemini-cli-oauth` 提供商
* 使用 Claude 协议调用 Gemini 模型:可使用 `gemini-cli-oauth` 提供商
* 使用 Claude 协议调用 OpenAI 模型:可使用 `openai-custom``openai-qwen-oauth` 提供商
### 🚀 突破限制,提升效率
* **绕过官方限制**:利用 OAuth 授权机制,有效突破 Gemini 等服务的免费 API 速率和配额限制
* **免费高级模型**:通过 Kiro API 模式免费使用 Claude Sonnet 4.5,通过 Qwen OAuth 模式使用 Qwen3 Coder Plus降低使用成本
* **账号池智能调度**:支持多账号轮询、自动故障转移和配置降级,确保 99.9% 服务可用性
### 🛡️ 安全可控,数据透明
* **全链路日志记录**:捕获所有请求和响应数据,支持审计、调试
* **私有数据集构建**:基于日志数据快速构建专属训练数据集
* **系统提示词管理**:支持覆盖和追加两种模式,实现统一基础指令与个性化扩展的完美结合
### 🔧 开发友好,易于扩展
* **模块化架构**:基于策略模式和适配器模式,新增模型提供商仅需 3 步
* **完整测试保障**:集成测试和单元测试覆盖率 90%+,确保代码质量
* **容器化部署**:提供 Docker 支持,一键部署,跨平台运行
* **MCP 协议支持**:完美兼容 Model Context Protocol轻松扩展功能
---
@ -53,8 +73,6 @@
- [🐳 Docker 部署](https://aiproxy.justlikemaki.vip/zh/docs/installation/docker-deployment.html)
- [🎨 模型协议与提供商关系图](#-模型协议与提供商关系图)
- [🔧 使用说明](#-使用说明)
- [💻 代理设置](#-代理设置)
- [🌟 特殊用法与进阶技巧](#-特殊用法与进阶技巧)
- [🚀 项目启动参数](#-项目启动参数)
- [📄 开源许可](#-开源许可)
- [🙏 致谢](#-致谢)
@ -115,134 +133,123 @@
## 🔧 使用说明
* **MCP 支持**:本项目完美支持 MCP (Model Context Protocol),可配合支持 MCP 的客户端实现功能扩展。
* **多模态能力**: 支持图片、文档等多模态输入,为您提供更丰富的交互体验。
* **最新模型支持**: 支持最新的 **Kimi K2**、**GLM-4.5** 和 **Qwen Code** 模型,只需在 `config.json` 中配置相应的 OpenAI 或 Claude 兼容接口即可使用。
* **Qwen Code 支持**
* **授权流程**:首次使用 Qwen Code 时,会自动在浏览器中打开授权页面。完成授权后,`oauth_creds.json` 文件将生成并存储在 `~/.qwen` 目录下。
* **模型参数**:请使用官方默认参数 `temperature=0``top_p=1`
* **Kiro API**
* **使用前提**:使用 Kiro API 需要[下载 Kiro 客户端](https://aibook.ren/archives/kiro-install)并完成授权登录,以生成 `kiro-auth-token.json` 文件。
* **最佳体验**:推荐配合 Claude Code 使用以获得最佳体验。
* **注意事项**Kiro 服务政策已调整,请查阅官方公告了解具体使用限制。
* **OpenAI Responses API**:
* **功能说明**: 支持 OpenAI Responses API 端点,提供更结构化的对话响应能力,适用于需要高级对话管理的应用场景。
* **配置方法**: 在 `config.json` 或启动参数中设置 `MODEL_PROVIDER``openaiResponses-custom`,并提供相应的 API 密钥和基础 URL。
* **模型供应商切换**:本项目支持通过 Path 路由和环境变量两种方式,在 API 调用中灵活切换不同的模型供应商。
### 📋 核心功能
#### 通过 Path 路由切换
通过在 API 请求路径中包含特定的供应商标识,您可以直接调用对应的模型:
* `http://localhost:3000/claude-custom` - 使用配置文件中定义的 Claude API 供应商。
* `http://localhost:3000/claude-kiro-oauth` - 使用 Kiro OAuth 认证方式访问 Claude API。
* `http://localhost:3000/openai-custom` - 使用 OpenAI 自定义供应商处理 Claude 请求。
* `http://localhost:3000/gemini-cli-oauth` - 使用 Gemini CLI OAuth 供应商处理 Claude 请求。
* `http://localhost:3000/openai-qwen-oauth` - 使用 Qwen OAuth 供应商处理 Claude 请求。
* `http://localhost:3000/openaiResponses-custom` - 使用 OpenAI Responses API 供应商处理结构化对话请求。
#### MCP 协议支持
本项目完全兼容 **Model Context Protocol (MCP)**,可与支持 MCP 的客户端无缝集成,实现强大的功能扩展。
这些 Path 路由不仅适用于直接 API 调用,也可在 Cline、Kilo 等编程 Agent 中配置 API 端点时使用,实现灵活的模型调用。例如,将 Agent 的 API 端点设置为 `http://localhost:3000/claude-kiro-oauth` 即可调用通过 Kiro OAuth 认证的 Claude 模型。
#### 多模态输入能力
支持图片、文档等多种类型的输入,为您提供更丰富的交互体验和更强大的应用场景。
#### 通过环境变量配置 Claude 参数
除了 Path 路由,您还可以通过设置以下环境变量来配置 Claude 相关的参数:
* `ANTHROPIC_BASE_URL`: 设置 Claude API 的基础 URL 路径。
* `ANTHROPIC_AUTH_TOKEN`: 设置 Claude 服务的认证密钥。
* `ANTHROPIC_MODEL`: 设置需要使用的 Claude 模型。
#### 不同系统中的环境变量设置方法
当使用 `http://localhost:3000/claude-custom` 路径时,可以通过以下方式设置环境变量:
##### Linux / macOS
```bash
export ANTHROPIC_BASE_URL="http://localhost:3000/claude-custom"
export ANTHROPIC_AUTH_TOKEN="your-auth-token-here"
export ANTHROPIC_MODEL="your-model-name"
```
##### Windows (CMD)
```cmd
set ANTHROPIC_BASE_URL=http://localhost:3000/claude-custom
set ANTHROPIC_AUTH_TOKEN=your-auth-token-here
set ANTHROPIC_MODEL=your-model-name
```
##### Windows (PowerShell)
```powershell
$env:ANTHROPIC_BASE_URL="http://localhost:3000/claude-custom"
$env:ANTHROPIC_AUTH_TOKEN="your-auth-token-here"
$env:ANTHROPIC_MODEL="your-model-name"
```
### 授权文件默认路径
以下是各服务授权文件的默认存储路径:
* **Gemini**: `~/.gemini/oauth_creds.json`
* **Kiro**: `~/.aws/sso/cache/kiro-auth-token.json`
* **Qwen**: `~/.qwen/oauth_creds.json`
其中 `~` 代表用户主目录。如果需要自定义路径,可以通过配置文件或环境变量进行设置。
#### 最新模型支持
无缝支持以下最新大模型,仅需在 [`config.json`](./config.json) 中配置相应的 OpenAI 或 Claude 兼容接口:
* **Kimi K2** - 月之暗面最新旗舰模型
* **GLM-4.5** - 智谱 AI 最新版本
* **Qwen Code** - 阿里通义千问代码专用模型
---
### 🔐 授权配置指南
## 💻 代理设置
#### Gemini CLI OAuth 配置
1. **获取OAuth凭据**:访问 [Google Cloud Console](https://console.cloud.google.com/) 创建项目启用Gemini API
2. **首次授权**使用Gemini服务后命令行会打印Google授权页面复制页面到浏览器授权完成后返回命令行
3. **凭据存储**:授权成功后,`oauth_creds.json` 文件将自动生成并保存至 `~/.gemini` 目录
4. **项目配置**需要提供有效的Google Cloud项目ID可通过启动参数 `--project-id` 指定
> **提示**: 如果您在无法直接访问 Google/OpenAI/Claude/Kiro 服务的环境中使用,请先为您的终端设置 HTTP代理不要设置 HTTPS代理。
#### Qwen Code OAuth 配置
1. **首次授权**:启动服务后,系统会自动在浏览器中打开授权页面
2. **凭据存储**:授权成功后,`oauth_creds.json` 文件将自动生成并保存至 `~/.qwen` 目录
3. **推荐参数**:使用官方默认参数以获得最佳效果
```json
{
"temperature": 0,
"top_p": 1
}
```
### 不同终端环境下的 HTTP 代理设置命令
#### Kiro API 配置
1. **环境准备**[下载并安装 Kiro 客户端](https://aibook.ren/archives/kiro-install)
2. **完成授权**:在客户端中登录账号,生成 `kiro-auth-token.json` 凭据文件
3. **最佳实践**:推荐配合 **Claude Code** 使用,可获得最优体验
4. **重要提示**Kiro 服务使用政策已更新,请访问官方网站查看最新使用限制和条款
为确保 `AIClient2API` 正常访问外部 AI 服务(如 Google、OpenAI、Claude、Kiro 等),您需要在终端环境中设置 HTTP 代理。以下是针对不同操作系统的代理设置命令:
#### OpenAI Responses API
* **应用场景**:适用于需要使用 OpenAI Responses API 进行结构化对话的场景如Codex
* **配置方法**
* 方式一:在 [`config.json`](./config.json) 中设置 `MODEL_PROVIDER``openaiResponses-custom`
* 方式二:使用启动参数 `--model-provider openaiResponses-custom`
* 方式三:使用路径路由 `/openaiResponses-custom`
* **必需参数**:提供有效的 API 密钥和基础 URL
---
### 🔄 模型供应商切换
本项目提供两种灵活的模型切换方式,满足不同使用场景的需求。
#### 方式一:启动参数切换
通过命令行参数指定默认使用的模型提供商:
#### Linux / macOS
```bash
export HTTP_PROXY="http://your_proxy_address:port"
# 如果代理需要认证
# export HTTP_PROXY="http://username:password@your_proxy_address:port"
```
要使这些设置永久生效,您可以将它们添加到您的 shell 配置文件中(例如 `~/.bashrc`, `~/.zshrc``~/.profile`)。
# 使用Gemini提供商
node src/api-server.js --model-provider gemini-cli-oauth --project-id your-project-id
#### Windows (CMD)
```cmd
set HTTP_PROXY=http://your_proxy_address:port
:: 如果代理需要认证
:: set HTTP_PROXY=http://username:password@your_proxy_address:port
```
这些设置只对当前 CMD 会话有效。如需永久设置,您可以通过系统环境变量进行配置。
# 使用Claude Kiro提供商
node src/api-server.js --model-provider claude-kiro-oauth
#### Windows (PowerShell)
```powershell
$env:HTTP_PROXY="http://your_proxy_address:port"
# 如果代理需要认证
# $env:HTTP_PROXY="http://username:password@your_proxy_address:port"
# 使用Qwen提供商
node src/api-server.js --model-provider openai-qwen-oauth
```
这些设置只对当前 PowerShell 会话有效。如需永久设置,您可以将它们添加到您的 PowerShell 配置文件中 (`$PROFILE`) 或通过系统环境变量进行配置。
**请务必将 `your_proxy_address``port` 替换为您的实际代理地址和端口。**
**可用的模型提供商标识**
- `openai-custom` - 标准OpenAI API
- `claude-custom` - 官方Claude API
- `gemini-cli-oauth` - Gemini CLI OAuth
- `claude-kiro-oauth` - Kiro Claude OAuth
- `openai-qwen-oauth` - Qwen Code OAuth
- `openaiResponses-custom` - OpenAI Responses API
#### 方式二Path 路由切换(推荐)
通过在 API 请求路径中指定供应商标识,实现即时切换:
| 路由路径 | 说明 | 适用场景 |
|---------|------|---------|
| `/claude-custom` | 使用配置文件中的 Claude API | 官方 Claude API 调用 |
| `/claude-kiro-oauth` | 通过 Kiro OAuth 访问 Claude | 免费使用 Claude Sonnet 4.5 |
| `/openai-custom` | 使用 OpenAI 供应商处理请求 | 标准 OpenAI API 调用 |
| `/gemini-cli-oauth` | 通过 Gemini CLI OAuth 访问 | 突破 Gemini 免费限制 |
| `/openai-qwen-oauth` | 通过 Qwen OAuth 访问 | 使用 Qwen Code Plus |
| `/openaiResponses-custom` | OpenAI Responses API | 结构化对话场景 |
**使用示例**
```bash
# 在 Cline、Kilo 等编程 Agent 中配置
API_ENDPOINT=http://localhost:3000/claude-kiro-oauth
# 直接 API 调用
curl http://localhost:3000/gemini-cli-oauth/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model":"gemini-2.0-flash-exp","messages":[...]}'
```
---
## 🌟 特殊用法与进阶技巧
### 📁 授权文件存储路径
* **🔌 对接任意 OpenAI 客户端**:这是本项目的核心功能。将任何支持 OpenAI 兼容 API 的应用(如 LobeChat, NextChat, VS Code 插件等)的 API 地址配置为指向本项目服务 (`http://localhost:3000`),即可无缝使用所有已配置的大模型。
各服务的授权凭据文件默认存储位置:
* **🔍 中心化请求监控与审计**:通过在 `config.json` 中设置 `"PROMPT_LOG_MODE": "file"`,可以捕获并记录所有发送给模型的请求(包括提示词)和接收到的响应,并保存到本地日志文件。这对于后续的审计、调试、提示词优化,以及构建私有数据集都具有重要价值。
| 服务 | 默认路径 | 说明 |
|------|---------|------|
| **Gemini** | `~/.gemini/oauth_creds.json` | OAuth 认证凭据 |
| **Kiro** | `~/.aws/sso/cache/kiro-auth-token.json` | Kiro 认证令牌 |
| **Qwen** | `~/.qwen/oauth_creds.json` | Qwen OAuth 凭据 |
* **💡 动态系统提示词**:通过配置 `config.json` 中的 `SYSTEM_PROMPT_FILE_PATH``SYSTEM_PROMPT_MODE` 参数,可以灵活控制系统提示词的行为,实现对模型预设指令的定制化管理。
* **可用模式**:
* `override`: 强制使用指定文件中的系统提示词,完全覆盖客户端发送的提示词。
* `append`: 在客户端发送的系统提示词末尾追加指定文件中的内容,作为补充指令。
* 此功能支持为不同客户端设置统一的基础指令,同时允许应用进行个性化扩展。
* **🛠️ 作为二次开发基石**
* **添加新模型提供商**:在 `src` 目录下创建新的提供商目录,实现 `ApiServiceAdapter` 接口及相应策略,并在 `adapter.js``common.js` 中注册即可轻松集成新的大模型服务。
* **响应缓存**:通过引入缓存机制,可针对高频重复请求进行响应缓存,有效降低 API 调用次数,显著提升响应速度。
* **自定义内容过滤**:在请求发送前或接收响应后,可自定义添加关键词过滤或内容审查逻辑,以满足特定的合规性或安全要求。
* **🎯 账号池高级配置**
* **多账号管理**:通过配置 `provider_pools.json` 文件,可为每个模型提供商设置多个账号,实现智能轮询,提高资源利用率。
* **故障转移**:当检测到某个账号失效时,系统将自动切换至下一个可用账号,确保服务的持续稳定运行。
* **配置降级**:支持根据账号的实时状态动态调整配置参数,例如在特定情况下自动切换到低消耗模型,以优化资源使用效率。
* **使用示例**:请参考项目提供的 `provider_pools.json` 配置文件示例,以便轻松配置多账号环境。
> **说明**`~` 表示用户主目录Windows: `C:\Users\用户名`Linux/macOS: `/home/用户名``/Users/用户名`
>
> **自定义路径**:可通过配置文件中的相关参数或环境变量指定自定义存储位置
---

View file

@ -447,7 +447,7 @@ let providerPoolManager = null;
async function initApiService(config) {
if (config.providerPools && Object.keys(config.providerPools).length > 0) {
providerPoolManager = new ProviderPoolManager(config.providerPools);
providerPoolManager = new ProviderPoolManager(config.providerPools, { globalConfig: config });
console.log('[Initialization] ProviderPoolManager initialized with configured pools.');
// 可以选择在这里触发一次健康检查
providerPoolManager.performHealthChecks();

View file

@ -17,6 +17,8 @@ export class ClaudeApiService {
this.config = config;
this.apiKey = config.CLAUDE_API_KEY;
this.baseUrl = config.CLAUDE_BASE_URL;
this.useSystemProxy = config?.USE_SYSTEM_PROXY_CLAUDE ?? false;
console.log(`[Claude] System proxy ${this.useSystemProxy ? 'enabled' : 'disabled'}`);
this.client = this.createClient();
}
@ -25,14 +27,21 @@ export class ClaudeApiService {
* @returns {object} Axios instance.
*/
createClient() {
return axios.create({
const axiosConfig = {
baseURL: this.baseUrl,
headers: {
'x-api-key': this.apiKey,
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01', // Claude API 版本
},
});
};
// 禁用系统代理以避免HTTPS代理错误
if (!this.useSystemProxy) {
axiosConfig.proxy = false;
}
return axios.create(axiosConfig);
}
/**

View file

@ -231,6 +231,8 @@ export class KiroApiService {
this.config = config;
this.credPath = config.KIRO_OAUTH_CREDS_DIR_PATH || path.join(os.homedir(), ".aws", "sso", "cache");
this.credsBase64 = config.KIRO_OAUTH_CREDS_BASE64;
this.useSystemProxy = config?.USE_SYSTEM_PROXY_KIRO ?? false;
console.log(`[Kiro] System proxy ${this.useSystemProxy ? 'enabled' : 'disabled'}`);
// this.accessToken = config.KIRO_ACCESS_TOKEN;
// this.refreshToken = config.KIRO_REFRESH_TOKEN;
// this.clientId = config.KIRO_CLIENT_ID;
@ -265,18 +267,24 @@ export class KiroApiService {
console.log('[Kiro] Initializing Kiro API Service...');
await this.initializeAuth();
const macSha256 = await getMacAddressSha256();
this.axiosInstance = axios.create({
const axiosConfig = {
timeout: KIRO_CONSTANTS.AXIOS_TIMEOUT,
headers: {
headers: {
'Content-Type': KIRO_CONSTANTS.CONTENT_TYPE_JSON,
'x-amz-user-agent': `aws-sdk-js/1.0.7 KiroIDE-0.1.25-${macSha256}`,
'user-agent': `aws-sdk-js/1.0.7 ua/2.1 os/win32#10.0.26100 lang/js md/nodejs#20.16.0 api/codewhispererstreaming#1.0.7 m/E KiroIDE-0.1.25-${macSha256}`,
'amz-sdk-request': 'attempt=1; max=1',
'x-amzn-kiro-agent-mode': 'vibe',
'Content-Type': KIRO_CONSTANTS.CONTENT_TYPE_JSON,
'Accept': KIRO_CONSTANTS.ACCEPT_JSON,
}
});
},
};
// 根据 useSystemProxy 配置代理设置
if (!this.useSystemProxy) {
axiosConfig.proxy = false;
}
this.axiosInstance = axios.create(axiosConfig);
this.isInitialized = true;
}

View file

@ -15,7 +15,7 @@ export const MODEL_PROTOCOL_PREFIX = {
// Model provider constants
GEMINI: 'gemini',
OPENAI: 'openai',
OPENAI_RESPONSES: 'openairesp',
OPENAI_RESPONSES: 'openaiResponses',
CLAUDE: 'claude',
}

View file

@ -9,13 +9,23 @@ export class OpenAIApiService {
this.config = config;
this.apiKey = config.OPENAI_API_KEY;
this.baseUrl = config.OPENAI_BASE_URL;
this.axiosInstance = axios.create({
this.useSystemProxy = config?.USE_SYSTEM_PROXY_OPENAI ?? false;
console.log(`[OpenAI] System proxy ${this.useSystemProxy ? 'enabled' : 'disabled'}`);
const axiosConfig = {
baseURL: this.baseUrl,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
}
});
},
};
// 禁用系统代理以避免HTTPS代理错误
if (!this.useSystemProxy) {
axiosConfig.proxy = false;
}
this.axiosInstance = axios.create(axiosConfig);
}
async callApi(endpoint, body, isRetry = false, retryCount = 0) {

View file

@ -44,6 +44,50 @@ export const qwenOAuth2Events = new EventEmitter();
// --- Helper Functions ---
// 封装公共的 await fetch 方法
async function commonFetch(url, options = {}, useSystemProxy = false) {
const defaultOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
};
// 合并默认选项和传入的选项
const mergedOptions = {
...defaultOptions,
...options,
headers: {
...defaultOptions.headers,
...options.headers,
},
};
// 如果不使用系统代理,设置空的代理配置
// 注意: Node.js 的 fetch 实现会自动使用环境变量中的代理设置
// 这里通过设置 agent 为 null 来尝试禁用代理
if (!useSystemProxy && typeof mergedOptions.agent === 'undefined') {
// 对于 Node.js fetch,我们可以通过设置 dispatcher 来控制代理
// 但这需要 undici 支持,这里我们先记录日志
console.debug('[Qwen] System proxy disabled for fetch request');
}
const response = await fetch(url, mergedOptions);
// 检查响应是否成功
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
error.status = response.status;
error.data = errorData;
throw error;
}
// 返回 JSON 响应
return await response.json();
}
function generateCodeVerifier() {
return crypto.randomBytes(32).toString('base64url');
}
@ -108,6 +152,18 @@ export class TokenManagerError extends Error {
}
}
/**
* 自定义错误类,用于指示需要清除凭证
* 当令牌刷新时发生 400 错误时抛出,表示刷新令牌已过期或无效
*/
export class CredentialsClearRequiredError extends Error {
constructor(message, originalError) {
super(message);
this.name = 'CredentialsClearRequiredError';
this.originalError = originalError;
}
}
// --- Core Service Class ---
@ -115,10 +171,12 @@ export class QwenApiService {
constructor(config) {
this.config = config;
this.isInitialized = false;
this.qwenClient = new QwenOAuth2Client();
this.sharedManager = SharedTokenManager.getInstance();
this.currentAxiosInstance = null;
this.tokenManagerOptions = { credentialFilePath: this._getQwenCachedCredentialPath() };
this.useSystemProxy = config?.USE_SYSTEM_PROXY_QWEN ?? false;
console.log(`[Qwen] System proxy ${this.useSystemProxy ? 'enabled' : 'disabled'}`);
this.qwenClient = new QwenOAuth2Client(config, this.useSystemProxy);
}
async initialize() {
@ -126,13 +184,21 @@ export class QwenApiService {
console.log('[Qwen] Initializing Qwen API Service...');
await this._initializeAuth();
this.currentAxiosInstance = axios.create({
const axiosConfig = {
baseURL: DEFAULT_QWEN_BASE_URL,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer `,
},
});
};
// 禁用系统代理
if (!this.useSystemProxy) {
axiosConfig.proxy = false;
}
this.currentAxiosInstance = axios.create(axiosConfig);
this.isInitialized = true;
console.log('[Qwen] Initialization complete.');
@ -432,14 +498,25 @@ export class QwenApiService {
try {
const { token, endpoint: qwenBaseUrl } = await this.getValidToken();
this.currentAxiosInstance = axios.create({
const axiosConfig = {
baseURL: qwenBaseUrl,
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` ,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
'X-DashScope-CacheControl': 'enable',
'X-DashScope-UserAgent': userAgent,
'X-DashScope-AuthType': 'qwen-oauth',
},
});
// 添加 HTTPS 代理修复相关配置
httpsAgent: undefined, // axios-https-proxy-fix 会自动处理
};
// 禁用系统代理
if (!this.useSystemProxy) {
axiosConfig.proxy = false;
}
this.currentAxiosInstance = axios.create(axiosConfig);
// Process message content before sending the request
const processedBody = body;//this.processMessageContent(body);
@ -720,7 +797,17 @@ class SharedTokenManager {
} catch (error) {
if (error instanceof TokenManagerError) throw error;
// If refresh token is invalid/expired, remove the corresponding credential file for this context
// 处理 CredentialsClearRequiredError - 清除凭证文件
if (error instanceof CredentialsClearRequiredError) {
try {
await fs.unlink(context.credentialFilePath);
console.log('[Qwen Auth] Credentials cleared due to refresh token expiry');
} catch (_) { /* ignore */ }
throw error; // 重新抛出以便上层处理
}
// 如果刷新令牌无效/过期,删除此上下文对应的凭证文件
if (error && (error.status === 400 || /expired|invalid/i.test(error.message || ''))) {
try { await fs.unlink(context.credentialFilePath); } catch (_) { /* ignore */ }
}
@ -790,6 +877,11 @@ class SharedTokenManager {
class QwenOAuth2Client {
credentials = {};
constructor(config, useSystemProxy = false) {
this.config = config;
this.useSystemProxy = useSystemProxy;
}
setCredentials(credentials) { this.credentials = credentials; }
getCredentials() { return this.credentials; }
@ -800,20 +892,27 @@ class QwenOAuth2Client {
refresh_token: this.credentials.refresh_token,
client_id: QWEN_OAUTH_CLIENT_ID,
};
const response = await fetch(QWEN_OAUTH_TOKEN_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
body: objectToUrlEncoded(bodyData),
});
if (!response.ok) {
if (response.status === 400) {
const err = new Error("Refresh token expired or invalid.");
err.status = 400;
throw err;
try {
const response = await commonFetch(QWEN_OAUTH_TOKEN_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
body: objectToUrlEncoded(bodyData),
}, this.useSystemProxy);
return response;
} catch (error) {
const errorData = error.data || {};
// 处理 400 错误,可能表示刷新令牌已过期
if (error.status === 400) {
// 清除凭证将由 SharedTokenManager 处理
throw new CredentialsClearRequiredError(
"刷新令牌已过期或无效。请使用 '/auth' 重新认证。",
{ status: error.status, response: errorData }
);
}
throw new Error(`Token refresh failed: ${response.status}`);
throw new Error(
`Token refresh failed: ${error.status || 'Unknown'} - ${errorData.error_description || error.message || 'No details'}`
);
}
return await response.json();
}
async requestDeviceAuthorization(options) {
@ -823,13 +922,16 @@ class QwenOAuth2Client {
code_challenge: options.code_challenge,
code_challenge_method: options.code_challenge_method,
};
const response = await fetch(QWEN_OAUTH_DEVICE_CODE_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
body: objectToUrlEncoded(bodyData),
});
if (!response.ok) throw new Error(`Device authorization failed: ${response.status}`);
return await response.json();
try {
const response = await commonFetch(QWEN_OAUTH_DEVICE_CODE_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
body: objectToUrlEncoded(bodyData),
}, this.useSystemProxy);
return response;
} catch (error) {
throw new Error(`Device authorization failed: ${error.status || error.message}`);
}
}
async pollDeviceToken(options) {
@ -839,23 +941,36 @@ class QwenOAuth2Client {
device_code: options.device_code,
code_verifier: options.code_verifier,
};
const response = await fetch(QWEN_OAUTH_TOKEN_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
body: objectToUrlEncoded(bodyData),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
if (response.status === 400 && errorData.error === 'authorization_pending') {
try {
const response = await commonFetch(QWEN_OAUTH_TOKEN_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
body: objectToUrlEncoded(bodyData),
}, this.useSystemProxy);
return response;
} catch (error) {
// 根据 OAuth RFC 8628,处理标准轮询响应
// 尝试解析错误响应为 JSON
const errorData = error.data || {};
const status = error.status;
// 用户尚未批准授权请求,继续轮询
if (status === 400 && errorData.error === 'authorization_pending') {
return { status: 'pending' };
}
if (response.status === 429 && errorData.error === 'slow_down') {
// 客户端轮询过于频繁,返回 pending 并设置 slowDown 标志
if (status === 429 && errorData.error === 'slow_down') {
return { status: 'pending', slowDown: true };
}
const error = new Error(`Device token poll failed: ${errorData.error || response.status}`);
error.status = response.status;
throw error;
// 处理其他 400 错误(access_denied, expired_token 等)作为真正的错误
// 对于其他错误,抛出适当的错误信息
const err = new Error(
`Device token poll failed: ${errorData.error || 'Unknown error'} - ${errorData.error_description || 'No details provided'}`
);
err.status = status;
throw err;
}
return await response.json();
}
}

View file

@ -8,6 +8,7 @@ import { MODEL_PROVIDER } from './common.js';
export class ProviderPoolManager {
constructor(providerPools, options = {}) {
this.providerPools = providerPools;
this.globalConfig = options.globalConfig || {}; // 存储全局配置
this.providerStatus = {}; // Tracks health and usage for each provider instance
this.roundRobinIndex = {}; // Tracks the current index for round-robin selection for each provider type
this.maxErrorCount = options.maxErrorCount || 3; // Default to 1 errors before marking unhealthy
@ -187,7 +188,17 @@ export class ProviderPoolManager {
async _checkProviderHealth(providerType, providerConfig) {
try {
// Create a temporary service adapter for health check
const tempConfig = { ...providerConfig, MODEL_PROVIDER: providerType };
// 合并全局配置和 provider 配置
const tempConfig = {
// ...this.globalConfig,
...providerConfig,
MODEL_PROVIDER: providerType,
USE_SYSTEM_PROXY_GEMINI: this.globalConfig.USE_SYSTEM_PROXY_GEMINI,
USE_SYSTEM_PROXY_OPENAI: this.globalConfig.USE_SYSTEM_PROXY_OPENAI,
USE_SYSTEM_PROXY_CLAUDE: this.globalConfig.USE_SYSTEM_PROXY_CLAUDE,
USE_SYSTEM_PROXY_QWEN: this.globalConfig.USE_SYSTEM_PROXY_QWEN,
USE_SYSTEM_PROXY_KIRO: this.globalConfig.USE_SYSTEM_PROXY_KIRO,
};
const serviceAdapter = getServiceAdapter(tempConfig);
if(!providerConfig.checkHealth){
return true;