docs: 移除独立的Docker文档并整合到主README

删除README.Docker.md文件并将Docker相关内容整合到主README中
更新README.md和README-EN.md,添加文档链接和免责声明
简化项目架构说明,突出核心功能和使用指南
This commit is contained in:
hex2077 2025-08-10 23:48:43 +08:00
parent a68ff027b9
commit 49aad4009f
3 changed files with 49 additions and 598 deletions

View file

@ -14,8 +14,9 @@
[![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)
[**中文**](./README.md) | [**English**](./README-EN.md)
[**中文**](./README.md) | [**English**](./README-EN.md) | [**More Detailed Documentation**](https://aiproxy.justlikemaki.vip/)
</div>
@ -35,52 +36,6 @@
---
## 📝 Project Architecture
Moving beyond a simple structure, we've implemented a more professional and extensible design, completely transforming the project:
* **`src/api-server.js`**: 🚀 **Project Entry Point**
* As the project's central orchestrator, it's responsible for launching and managing the entire HTTP service, parsing command-line arguments, and loading all configurations.
* **`src/adapter.js`**: 🔌 **Service Adapter**
* Adopts the classic adapter pattern, creating a unified interface for each AI service (Gemini, OpenAI, Claude, Kiro). Regardless of backend service variations, the main service interacts with them consistently.
* **`src/provider-strategies.js`**: 🎯 **Provider Strategy Factory**
* Implements the strategy factory pattern, offering unified strategy interfaces for each API protocol (e.g., OpenAI, Gemini, Claude). These strategies precisely handle request parsing, response formatting, model name extraction, and all other protocol-specific details, ensuring seamless conversion between protocols.
* **`src/provider-strategy.js`**: 🎯 **Strategy Base Class**
* Defines the foundational interface and common methods for all provider strategies, including core functionalities like system prompt management and content extraction.
* **`src/convert.js`**: 🔄 **Format Conversion Hub**
* This is the core magic enabling "everything OpenAI-compatible." It precisely and losslessly converts data between different API protocol formats.
* **`src/common.js`**: 🛠️ **Common Utility Library**
* Contains shared constants, utility functions, and common handlers for the project, leading to cleaner and more efficient code.
* **`src/gemini/`, `src/openai/`, `src/claude/`**: 📦 **Provider Implementation Directories**
* Each directory encapsulates the core logic, API calls, and strategy implementations for its respective service provider, offering a clear structure that simplifies adding new service providers in the future. `src/claude/claude-kiro.js` specifically provides the Kiro API implementation.
* **`tests/`**: 🧪 **Test Directory**
* Comprises a comprehensive integration test suite covering all API endpoints, authentication methods, and error handling scenarios, guaranteeing project stability and reliability. It supports independent testing for different providers and full HTTP integration tests.
### 🏗️ Architecture Design Patterns
The project leverages various modern design patterns to ensure code maintainability and extensibility:
* **Adapter Pattern**: `src/adapter.js` provides a unified interface for diverse AI services.
* **Strategy Pattern**: `src/provider-strategies.js` manages request/response conversion for different protocols.
* **Factory Pattern**: Dynamically creates and manages service adapter instances.
* **Singleton Pattern**: Caches and reuses service adapter instances.
### 🔄 Data Flow Processing
1. **Request Reception**: The HTTP server receives client requests.
2. **Authentication Validation**: Unified validation for multiple authentication methods.
3. **Protocol Identification**: Recognizes the client protocol based on the endpoint and request headers.
4. **Format Conversion**: Converts the request to the target provider's format.
5. **Service Invocation**: Calls the specific AI service via the adapter.
6. **Response Conversion**: Converts the service response back to the client's expected format.
7. **Streaming Processing**: Supports real-time streaming response transmission.
### 🎨 Model Protocol and Provider Relationship Diagram
@ -131,133 +86,13 @@ The project leverages various modern design patterns to ensure code maintainabil
* **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** and **GLM-4.5** models. Simply configure the corresponding OpenAI or Claude compatible interfaces in `config.json` for use.
* **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**.
* **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: New users who encounter **429** errors when using the service indicate that the Kiro service is **no longer available**, and may need to wait until Kiro fully opens registration before being able to use it.
---
## 🛠️ Key Features
## 💻 Proxy Settings
#### General Features
* 🔐 **Smart Authentication & Token Renewal**: For services requiring OAuth (e.g., `gemini-cli-oauth`), the initial run guides you through browser authorization and automatically refreshes tokens.
* 🛡️ **Multiple Authentication Methods**: Supports `Authorization: Bearer <key>`, `x-goog-api-key`, `x-api-key` request headers, and URL query parameters for authentication.
* ⚙️ **Highly Configurable**: Flexibly configure listening addresses, ports, API keys, model providers, and logging modes via `config.json` or command-line arguments.
* 📜 **Fully Controllable Logging System**: Can output timestamped prompt logs to the console or a file, and display remaining token validity.
* 🏥 **Health Check Mechanism**: Provides a `/health` endpoint for service status monitoring, returning service health and current configuration.
#### OpenAI Compatible Interface (`/v1/...`)
* 🌍 **Perfect Compatibility**: Implements the core `/v1/models` and `/v1/chat/completions` endpoints.
* 🔄 **Automatic Format Conversion**: Seamlessly converts requests/responses between different model formats and OpenAI format internally, supporting multimodal content.
* 💨 **Streaming Support**: Fully supports OpenAI's streaming responses (`"stream": true`), delivering a typewriter-like real-time experience.
#### Gemini Native Interface (`/v1beta/...`)
* 🎯 **Native Support**: Full support for Gemini API's native format and features.
* 🔧 **Advanced Features**: Supports system instructions, tool calls, multimodal input, and other advanced functionalities.
* 📊 **Detailed Statistics**: Provides comprehensive token usage statistics and model information.
#### Claude Native Interface (`/v1/messages`)
* 🤖 **Claude Dedicated**: Full support for Claude Messages API format.
* 🛠️ **Tool Integration**: Supports Claude's tool usage and function calling features.
* 🎨 **Multimodal**: Supports images, audio, and other input formats.
---
## 📦 Installation Guide
1. **Environment Preparation**:
* Please ensure [Node.js](https://nodejs.org/) is installed (recommended version >= 20.0.0).
* This project already includes `package.json` and sets `{"type": "module"}`, eliminating manual creation.
2. **Install Dependencies**:
After cloning this repository, execute the following in the project root directory:
```bash
npm install
```
This will automatically install all necessary dependencies.
---
## 🚀 Quick Start
### 1. Configuration File (`config.json`)
We recommend using the `config.json` file for configuration management, offering greater clarity than lengthy command-line arguments.
First, manually create a `config.json` file and populate it with your configuration details.
```json
{
"REQUIRED_API_KEY": "123456",
"SERVER_PORT": 3000,
"HOST": "localhost",
"MODEL_PROVIDER": "gemini-cli-oauth",
"OPENAI_API_KEY": "sk-your-openai-key",
"OPENAI_BASE_URL": "https://api.openai.com/v1",
"CLAUDE_API_KEY": "sk-ant-your-claude-key",
"CLAUDE_BASE_URL": "https://api.anthropic.com/v1",
"PROJECT_ID": "your-gcp-project-id",
"PROMPT_LOG_MODE": "console"
}
```
### 2. Configuration Parameter Details
The following table details all supported parameters in `config.json`:
| Parameter Name | Type | Description | Default/Optional Values |
| --- | --- | --- | --- |
| `REQUIRED_API_KEY` | string | Key to protect your API service. Clients must provide this key with requests. | Any string, defaults to `"123456"` |
| `SERVER_PORT` | number | Port number the server listens on. | Any valid port, defaults to `3000` |
| `HOST` | string | Host address the server listens on. `localhost` for local access, `0.0.0.0` for LAN/public access. | Defaults to `"localhost"` |
| `MODEL_PROVIDER` | string | Specifies backend model service provider. Core config determining API request forwarding. | Options: `"gemini-cli-oauth"`, `"openai-custom"`, `"claude-custom"`, `"claude-kiro-oauth"` |
| `OPENAI_API_KEY` | string | Required OpenAI API key when `MODEL_PROVIDER` is `openai-custom`. | `null` |
| `OPENAI_BASE_URL` | string | Optional OpenAI-compatible API address when `MODEL_PROVIDER` is `openai-custom`. | Defaults to `"https://api.openai.com/v1"` |
| `CLAUDE_API_KEY` | string | Required Claude API key when `MODEL_PROVIDER` is `claude-custom`. | `null` |
| `CLAUDE_BASE_URL` | string | Optional Claude-compatible API address when `MODEL_PROVIDER` is `claude-custom`. | Defaults to `"https://api.anthropic.com/v1"` |
| `KIRO_OAUTH_CREDS_BASE64` | string | (Kiro API Mode) Base64 encoded Kiro OAuth credentials string. | `null` |
| `KIRO_OAUTH_CREDS_FILE_PATH` | string | (Kiro API Mode) Path to your Kiro OAuth credentials JSON file. | `null` |
| `GEMINI_OAUTH_CREDS_BASE64` | string | (Gemini-CLI Mode) Base64 encoded Google OAuth credentials string. | `null` |
| `GEMINI_OAUTH_CREDS_FILE_PATH` | string | (Gemini-CLI Mode) Path to your Google OAuth credentials JSON file. | `null` |
| `PROJECT_ID` | string | (Gemini-CLI Mode) Your Google Cloud project ID. | `null` |
| `SYSTEM_PROMPT_FILE_PATH` | string | External file path for loading system prompts. | Defaults to `"input_system_prompt.txt"` |
| `SYSTEM_PROMPT_MODE` | string | System prompt application mode. `overwrite` overrides client prompt, `append` appends. | Options: `"overwrite"`, `"append"` |
| `PROMPT_LOG_MODE` | string | Logging mode for requests/responses. `none` (no log), `console` (to console), `file` (to log file). | Options: `"none"`, `"console"`, `"file"` |
| `PROMPT_LOG_BASE_NAME` | string | Base name for log files when `PROMPT_LOG_MODE` is `file`. | Defaults to `"prompt_log"` |
| `REQUEST_MAX_RETRIES` | number | Maximum number of automatic retries for failed API requests. | Defaults to `3` |
| `REQUEST_BASE_DELAY` | number | Base delay (milliseconds) between automatic retries. Delay increases with each retry. | Defaults to `1000` |
| `CRON_NEAR_MINUTES` | number | (Gemini-CLI Mode) Interval in minutes for the OAuth token refresh task. | Defaults to `15` |
| `CRON_REFRESH_TOKEN` | boolean | (Gemini-CLI Mode) Whether to enable automatic OAuth token refresh task. | Defaults to `true` |
### 3. Start the Service
* **Using `config.json`** (Recommended)
```bash
node src/api-server.js
```
* **Via Command-Line Arguments** (Overrides same-name settings in `config.json`)
* **Start OpenAI Proxy**:
```bash
node src/api-server.js --model-provider openai-custom --openai-api-key sk-xxx
```
* **Start Claude Proxy**:
```bash
node src/api-server.js --model-provider claude-custom --claude-api-key sk-ant-xxx
```
* **Start Kiro API Proxy**:
```bash
node src/api-server.js --model-provider claude-kiro-oauth
```
* **Listen on all network interfaces, specify port and key** (for Docker or LAN access)
```bash
node src/api-server.js --host 0.0.0.0 --port 8000 --api-key your_secret_key
```
*For more startup parameters, refer to the comments at the top of the `src/api-server.js` file.*
---
### 4. Call the API
> **Hint**: If you are using this in an environment where direct access to Google/OpenAI/Claude/Kiro services is unavailable, please set up a global HTTP/HTTPS proxy for your terminal first.
> **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.
### HTTP Proxy Setup Commands for Different Terminal Environments
@ -289,90 +124,8 @@ These settings are effective only for the current PowerShell session. For perman
**Please replace `your_proxy_address` and `port` with your actual proxy address and port.**
---
### 🐳 Docker Deployment
The project supports Docker deployment. For a detailed guide, please refer to the [Docker Deployment Guide](./README.Docker.md).
---
All requests use the standard OpenAI format.
* **Health Check**
```bash
curl http://localhost:3000/health
```
* **List Models**
```bash
curl http://localhost:3000/v1/models \
-H "Authorization: Bearer 123456"
```
* **Generate Content (Non-streaming)**
```bash
curl http://localhost:3000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456" \
-d '{
"model": "gemini-2.5-flash",
"messages": [
{"role": "system", "content": "You are a cat named Neko."},
{"role": "user", "content": "Hello, what is your name?"}
]
}'
```
* **Multimodal Content Generation**
```bash
curl http://localhost:3000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456" \
-d '{
"model": "gemini-2.5-flash",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "Describe this image"},
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,..."}}
]
}
]
}'
```
* **Using Different Providers (via Path)**
```bash
# Using Gemini
curl http://localhost:3000/gemini-cli-oauth/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456" \
-d '{"model": "gemini-2.5-flash", "messages": [{"role": "user", "content": "Hello"}]}'
# Using Claude
curl http://localhost:3000/claude-custom/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456" \
-d '{"model": "claude-3-opus-20240229", "messages": [{"role": "user", "content": "Hello"}]}'
```
* **Stream Generate Content**
```bash
curl http://localhost:3000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456" \
-d '{
"model": "claude-3-opus-20240229",
"messages": [
{"role": "user", "content": "Write a five-line poem about the universe"}
],
"stream": true
}'
```
---
## 🌟 Special Usage & Advanced Tips
* **🔌 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.
* **🔍 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.
@ -380,7 +133,7 @@ All requests use the standard OpenAI format.
* **💡 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**:
* `overwrite`: Completely ignores the client's system prompt, enforcing the content from the file.
* `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.
@ -402,3 +155,19 @@ The development of this project was significantly inspired by the official Googl
## 🌟 Star History
[![Star History Chart](https://api.star-history.com/svg?repos=justlovemaki/AIClient-2-API&type=Timeline)](https://www.star-history.com/#justlovemaki/AIClient-2-API&Timeline)
---
## ⚠️ Disclaimer
### Usage Risk Warning
This project (AIClient-2-API) 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.
### Legal Compliance Reminder
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.

View file

@ -1,93 +0,0 @@
# Docker部署指南
本指南将帮助您使用Docker部署AIClient2API服务。
## 构建Docker镜像
在项目根目录下执行以下命令来构建Docker镜像
```bash
docker build -t gemini-cli2api .
```
## 运行容器
### 基本运行
```bash
docker run -d -p 3000:3000 --name gemini-cli2api gemini-cli2api
```
### 通过ARGS环境变量配置服务
服务支持通过`ARGS`环境变量来配置,例如:
```bash
docker run -d \
-p 3000:3000 \
-e ARGS="--api-key 123456 --host 0.0.0.0" \
--name gemini-cli2api \
gemini-cli2api
```
### 使用Base64编码的凭据
项目包含两个脚本用于自动处理Base64编码的凭据
- `run-docker.bat` (Windows)
- `run-docker.sh` (Linux/Unix)
这些脚本会自动生成包含凭据的`ARGS`环境变量:
```bash
# Windows
run-docker.bat
# Linux/Unix (首次使用需要授予权限)
chmod +x run-docker.sh
./run-docker.sh
```
### 挂载配置文件和日志目录
```bash
# 挂载配置文件
docker run -d \
-p 3000:3000 \
-v /path/to/your/config.json:/app/config.json \
--name gemini-cli2api \
gemini-cli2api
# 挂载日志目录
docker run -d \
-p 3000:3000 \
-v /path/to/your/logs:/app/logs \
--name gemini-cli2api \
gemini-cli2api
```
## 访问服务
容器启动后您可以通过以下URL访问服务
```
http://localhost:3000
```
## 可用端点
- `POST /v1/chat/completions` - OpenAI兼容聊天完成端点
- `GET /v1/models` - OpenAI兼容模型列表端点
- `POST /v1beta/models/{model}:generateContent` - Gemini兼容内容生成端点
- `GET /v1beta/models` - Gemini兼容模型列表端点
- `GET /health` - 健康检查端点
## 故障排除
如果容器无法启动,请检查以下内容:
1. 确保端口3000未被其他进程占用
2. 检查环境变量配置是否正确
3. 查看容器日志以获取更多信息:
```bash
docker logs gemini-cli2api

279
README.md
View file

@ -14,8 +14,10 @@
[![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)
[**中文**](./README.md) | [**English**](./README-EN.md)
[**中文**](./README.md) | [**English**](./README-EN.md) | [**更详细文档**](https://aiproxy.justlikemaki.vip/)
</div>
@ -35,54 +37,7 @@
---
## 📝 项目架构
告别了过去简单的结构,我们引入了更专业、更具扩展性的设计模式,让项目脱胎换骨:
* **`src/api-server.js`**: 🚀 **项目启动入口**
* 作为项目的总指挥,它负责启动和管理整个 HTTP 服务,解析命令行参数,并加载所有配置。
* **`src/adapter.js`**: 🔌 **服务适配器**
* 采用经典的适配器模式,为每种 AI 服务Gemini, OpenAI, Claude, Kiro创建一个统一的接口。无论后端服务如何变化对主服务来说调用方式都是一致的。
* **`src/provider-strategies.js`**: 🎯 **提供商策略工厂**
* 实现了策略工厂模式,为每种 API 协议(如 OpenAI、Gemini、Claude提供统一的策略接口。这些策略精确地处理协议下的请求解析、响应格式化、模型名称提取等所有细节确保了协议之间的完美转换。
* **`src/provider-strategy.js`**: 🎯 **策略基类**
* 定义了所有提供商策略的基础接口和通用方法,包括系统提示词管理、内容提取等核心功能。
* **`src/convert.js`**: 🔄 **格式转换中心**
* 这是实现“万物皆可 OpenAI”魔法的核心。它负责在不同的 API 协议格式之间进行精确、无损的数据转换。
* **`src/common.js`**: 🛠️ **通用工具库**
* 存放着项目共享的常量、工具函数和通用处理器,让代码更加整洁和高效。
* **`src/gemini/`, `src/openai/`, `src/claude/`**: 📦 **提供商实现目录**
* 每个目录都包含了对应服务商的核心逻辑、API 调用和策略实现,结构清晰,便于您未来添加更多新的服务商。其中 `src/claude/claude-kiro.js` 提供了 Kiro API 的特殊实现。
* **`tests/`**: 🧪 **测试目录**
* 包含完整的集成测试套件覆盖所有API端点、认证方式和错误处理场景确保项目的稳定性和可靠性。支持针对不同提供商的独立测试和完整的HTTP集成测试。
### 🏗️ 架构设计模式
项目采用多种现代设计模式,确保代码的可维护性和扩展性:
* **适配器模式 (Adapter Pattern)**: `src/adapter.js` 为不同的 AI 服务提供统一接口
* **策略模式 (Strategy Pattern)**: `src/provider-strategies.js` 处理不同协议的请求/响应转换
* **工厂模式 (Factory Pattern)**: 动态创建和管理服务适配器实例
* **单例模式 (Singleton Pattern)**: 服务适配器实例的缓存和复用
### 🔄 数据流处理
1. **请求接收**: HTTP 服务器接收客户端请求
2. **认证验证**: 多种认证方式的统一验证
3. **协议识别**: 根据端点和请求头识别客户端协议
4. **格式转换**: 将请求转换为目标提供商格式
5. **服务调用**: 通过适配器调用具体的 AI 服务
6. **响应转换**: 将服务响应转换回客户端期望格式
7. **流式处理**: 支持实时流式响应传输
### 🎨 模型协议与提供商关系图
## 🎨 模型协议与提供商关系图
- OpenAI 协议 (P_OPENAI): 支持所有 MODEL_PROVIDER包括 openai-custom、gemini-cli-oauth、claude-custom 和
@ -126,138 +81,19 @@ claude-kiro-oauth。
---
### 🔧 使用说明
## 🔧 使用说明
* **MCP 支持**: 虽然原版 Gemini CLI 的内置命令功能不可用,但本项目完美支持 MCP (Model Context Protocol),可配合支持 MCP 的客户端实现更强大的功能扩展。
* **多模态能力**: 支持图片、文档等多模态输入,为您提供更丰富的交互体验。
* **最新模型支持**: 支持最新的 **Kimi K2****GLM-4.5** 模型,只需在 `config.json` 中配置相应的 OpenAI 或 Claude 兼容接口即可使用。
* **Kiro API**: 使用 Kiro API 需要[下载kiro客户端](https://aibook.ren/archives/kiro-install)并完成授权登录生成 kiro-auth-token.json。**推荐配合 Claude Code 使用以获得最佳体验**。
* **Kiro API**: 使用 Kiro API 需要[下载kiro客户端](https://aibook.ren/archives/kiro-install)并完成授权登录生成 kiro-auth-token.json。**推荐配合 Claude Code 使用以获得最佳体验**。注意:新注册的用户,如果使用时报**429**,表示**已不可使用** Kiro 的服务可能需要等Kiro完全开放注册后才能使用。
---
## 🛠️ 主要功能
#### 通用功能
* 🔐 **智能认证与令牌续期**: 针对需要 OAuth 的服务(如 `gemini-cli-oauth`),首次运行将引导您通过浏览器完成授权,并能自动刷新令牌。
* 🛡️ **多种认证方式支持**: 支持 `Authorization: Bearer <key>`、`x-goog-api-key`、`x-api-key` 请求头以及 URL 查询参数等多种认证方式。
* ⚙️ **高度可配置**: 可通过 `config.json` 文件或命令行参数灵活配置监听地址、端口、API 密钥、模型提供商以及日志模式。
* 📜 **全面可控的日志系统**: 可将带时间戳的提示词日志输出到控制台或文件,并显示令牌剩余有效期。
* 🏥 **健康检查机制**: 提供 `/health` 端点用于服务状态监控,返回服务健康状态和当前配置信息。
## 💻 代理设置
#### OpenAI 兼容接口 (`/v1/...`)
* 🌍 **完美兼容**: 实现了 `/v1/models``/v1/chat/completions` 核心端点。
* 🔄 **自动格式转换**: 在内部自动将不同模型的请求/响应与 OpenAI 格式进行无缝转换,支持多模态内容。
* 💨 **流式传输支持**: 完全支持 OpenAI 的流式响应 (`"stream": true`),提供打字机般的实时体验。
#### Gemini 原生接口 (`/v1beta/...`)
* 🎯 **原生支持**: 完整支持 Gemini API 的原生格式和功能。
* 🔧 **高级功能**: 支持系统指令、工具调用、多模态输入等高级特性。
* 📊 **详细统计**: 提供完整的 token 使用统计和模型信息。
#### Claude 原生接口 (`/v1/messages`)
* 🤖 **Claude 专用**: 完整支持 Claude Messages API 格式。
* 🛠️ **工具集成**: 支持 Claude 的工具使用和函数调用功能。
* 🎨 **多模态**: 支持图片、音频等多种输入格式。
---
## 📦 安装指南
1. **环境准备**:
* 请确保您已安装 [Node.js](https://nodejs.org/) (建议版本 >= 20.0.0)。
* 本项目已包含 `package.json` 并设置 `{"type": "module"}`,您无需手动创建。
2. **安装依赖**:
克隆本仓库后,在项目根目录下执行:
```bash
npm install
```
这将自动安装所有必要依赖。
---
## 🚀 快速开始
### 1. 配置文件 (`config.json`)
我们推荐使用 `config.json` 文件来管理您的配置,这比冗长的命令行参数更清晰。
首先,手动创建 `config.json` 文件,并填入您的配置信息。
```json
{
"REQUIRED_API_KEY": "123456",
"SERVER_PORT": 3000,
"HOST": "localhost",
"MODEL_PROVIDER": "gemini-cli-oauth",
"OPENAI_API_KEY": "sk-your-openai-key",
"OPENAI_BASE_URL": "https://api.openai.com/v1",
"CLAUDE_API_KEY": "sk-ant-your-claude-key",
"CLAUDE_BASE_URL": "https://api.anthropic.com/v1",
"PROJECT_ID": "your-gcp-project-id",
"PROMPT_LOG_MODE": "console"
}
```
### 2. 配置参数详解
以下是 `config.json` 文件中所有支持的参数及其详细说明:
| 参数名 | 类型 | 描述 | 默认值/可选值 |
| ------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `REQUIRED_API_KEY` | string | 用于保护您的 API 服务的密钥。客户端在请求时必须提供此密钥。 | 任意字符串, 默认为 `"123456"` |
| `SERVER_PORT` | number | 服务器监听的端口号。 | 任意有效端口号, 默认为 `3000` |
| `HOST` | string | 服务器监听的主机地址。`localhost` 只允许本机访问,`0.0.0.0` 允许局域网或公网访问。 | 默认为 `"localhost"` |
| `MODEL_PROVIDER` | string | 指定后端使用的模型服务商。这是核心配置,决定了 API 请求将转发给哪个平台。 | 可选值: `"gemini-cli-oauth"`, `"openai-custom"`, `"claude-custom"`, `"claude-kiro-oauth"` |
| `OPENAI_API_KEY` | string | 当 `MODEL_PROVIDER``openai-custom` 时,需要提供您的 OpenAI API 密钥。 | `null` |
| `OPENAI_BASE_URL` | string | 当 `MODEL_PROVIDER``openai-custom` 时,可以指定 OpenAI 兼容的 API 地址。 | 默认为 `"https://api.openai.com/v1"` |
| `CLAUDE_API_KEY` | string | 当 `MODEL_PROVIDER``claude-custom` 时,需要提供您的 Claude API 密钥。 | `null` |
| `CLAUDE_BASE_URL` | string | 当 `MODEL_PROVIDER``claude-custom` 时,可以指定 Claude 兼容的 API 地址。 | 默认为 `"https://api.anthropic.com/v1"` |
| `KIRO_OAUTH_CREDS_BASE64` | string | (Kiro API 模式) 您的 Kiro OAuth 凭据的 Base64 编码字符串。 | `null` |
| `KIRO_OAUTH_CREDS_FILE_PATH` | string | (Kiro API 模式) 您的 Kiro OAuth 凭据 JSON 文件的路径。 | `null` |
| `GEMINI_OAUTH_CREDS_BASE64` | string | (Gemini-CLI 模式) 您的 Google OAuth 凭据的 Base64 编码字符串。 | `null` |
| `GEMINI_OAUTH_CREDS_FILE_PATH` | string | (Gemini-CLI 模式) 您的 Google OAuth 凭据 JSON 文件的路径。 | `null` |
| `PROJECT_ID` | string | (Gemini-CLI 模式) 您的 Google Cloud 项目 ID。 | `null` |
| `SYSTEM_PROMPT_FILE_PATH` | string | 用于加载系统提示词的外部文件路径。 | 默认为 `"input_system_prompt.txt"` |
| `SYSTEM_PROMPT_MODE` | string | 系统提示词的应用模式。`overwrite` 会覆盖客户端的提示,`append` 会追加到客户端提示之后。 | 可选值: `"overwrite"`, `"append"` |
| `PROMPT_LOG_MODE` | string | 请求和响应的日志记录模式。`none` 不记录,`console` 打印到控制台,`file` 保存到日志文件。 | 可选值: `"none"`, `"console"`, `"file"` |
| `PROMPT_LOG_BASE_NAME` | string | 当 `PROMPT_LOG_MODE``file` 时,生成的日志文件的基础名称。 | 默认为 `"prompt_log"` |
| `REQUEST_MAX_RETRIES` | number | 当 API 请求失败时,自动重试的最大次数。 | 默认为 `3` |
| `REQUEST_BASE_DELAY` | number | 自动重试之间的基础延迟时间(毫秒)。每次重试后延迟会增加。 | 默认为 `1000` |
| `CRON_NEAR_MINUTES` | number | (Gemini-CLI 模式) OAuth 令牌刷新任务计划的间隔时间(分钟)。 | 默认为 `15` |
| `CRON_REFRESH_TOKEN` | boolean | (Gemini-CLI 模式) 是否开启 OAuth 令牌自动刷新任务。 | 默认为 `true` |
### 3. 启动服务
* **使用 `config.json` 启动** (推荐)
```bash
node src/api-server.js
```
* **通过命令行参数启动** (会覆盖 `config.json` 中的同名配置)
* **启动 OpenAI 代理**:
```bash
node src/api-server.js --model-provider openai-custom --openai-api-key sk-xxx
```
* **启动 Claude 代理**:
```bash
node src/api-server.js --model-provider claude-custom --claude-api-key sk-ant-xxx
```
* **启动 Kiro API 代理**:
```bash
node src/api-server.js --model-provider claude-kiro-oauth
```
* **监听所有网络接口并指定端口和Key** (用于 Docker 或局域网访问)
```bash
node src/api-server.js --host 0.0.0.0 --port 8000 --api-key your_secret_key
```
*更多启动参数,请参考 `src/api-server.js` 文件顶部的注释。*
---
### 4. 调用 API
> **提示**: 如果您在无法直接访问 Google/OpenAI/Claude/Kiro 服务的环境中使用,请先为您的终端设置全局 HTTP/HTTPS 代理。
> **提示**: 如果您在无法直接访问 Google/OpenAI/Claude/Kiro 服务的环境中使用,请先为您的终端设置 HTTP代理不要设置 HTTPS代理。
### 不同终端环境下的 HTTP 代理设置命令
@ -291,86 +127,6 @@ $env:HTTP_PROXY="http://your_proxy_address:port"
---
### 🐳 Docker 部署
项目支持通过 Docker 进行部署,详细指南请参阅 [Docker部署指南](./README.Docker.md)。
---
所有请求都使用标准的 OpenAI 格式。
* **健康检查**
```bash
curl http://localhost:3000/health
```
* **列出模型**
```bash
curl http://localhost:3000/v1/models \
-H "Authorization: Bearer 123456"
```
* **生成内容 (非流式)**
```bash
curl http://localhost:3000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456" \
-d '{
"model": "gemini-2.5-flash",
"messages": [
{"role": "system", "content": "你是一只名叫 Neko 的猫。"},
{"role": "user", "content": "你好,你叫什么名字?"}
]
}'
```
* **多模态内容生成**
```bash
curl http://localhost:3000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456" \
-d '{
"model": "gemini-2.5-flash",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "描述这张图片"},
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,..."}}
]
}
]
}'
```
* **使用不同提供商 (通过路径)**
```bash
# 使用 Gemini
curl http://localhost:3000/gemini-cli-oauth/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456" \
-d '{"model": "gemini-2.5-flash", "messages": [{"role": "user", "content": "Hello"}]}'
# 使用 Claude
curl http://localhost:3000/claude-custom/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456" \
-d '{"model": "claude-3-opus-20240229", "messages": [{"role": "user", "content": "Hello"}]}'
```
* **流式生成内容**
```bash
curl http://localhost:3000/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456" \
-d '{
"model": "claude-3-opus-20240229",
"messages": [
{"role": "user", "content": "写一首关于宇宙的五行短诗"}
],
"stream": true
}'
```
---
## 🌟 特殊用法与进阶技巧
* **🔌 对接任意 OpenAI 客户端**: 这是本项目的基本功能。将任何支持 OpenAI 的应用(如 LobeChat, NextChat, VS Code 插件等)的 API 地址指向本服务 (`http://localhost:3000`),即可无缝使用所有已配置的模型。
@ -402,3 +158,22 @@ $env:HTTP_PROXY="http://your_proxy_address:port"
## 🌟 Star History
[![Star History Chart](https://api.star-history.com/svg?repos=justlovemaki/AIClient-2-API&type=Timeline)](https://www.star-history.com/#justlovemaki/AIClient-2-API&Timeline)
---
## ⚠️ 免责声明
### 使用风险提示
本项目AIClient-2-API仅供学习和研究使用。用户在使用本项目时应自行承担所有风险。作者不对因使用本项目而导致的任何直接、间接或 consequential 损失承担责任。
### 第三方服务责任说明
本项目是一个API代理工具不提供任何AI模型服务。所有AI模型服务由相应的第三方提供商如Google、OpenAI、Anthropic等提供。用户在使用本项目访问这些第三方服务时应遵守各第三方服务的使用条款和政策。作者不对第三方服务的可用性、质量、安全性或合法性承担责任。
### 数据隐私说明
本项目在本地运行不会收集或上传用户的任何数据。但用户在使用本项目时应注意保护自己的API密钥和其他敏感信息。建议用户定期检查和更新自己的API密钥并避免在不安全的网络环境中使用本项目。
### 法律合规提醒
用户在使用本项目时,应遵守所在国家/地区的法律法规。严禁将本项目用于任何非法用途。如因用户违反法律法规而导致的任何后果,由用户自行承担全部责任。
---