tanbushi commited on
Commit
faae9a1
·
1 Parent(s): 9432aa8
app.py CHANGED
@@ -9,7 +9,6 @@ import logging # 导入logging模块
9
  from dotenv import load_dotenv
10
  from enum import Enum
11
  from proxy import do_proxy
12
- # from api_key_sb import get_api_key
13
 
14
  # 配置日志
15
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
@@ -39,7 +38,7 @@ def verify_proxy_api_key(credentials: HTTPAuthorizationCredentials = Depends(sec
39
  )
40
  return credentials.credentials
41
 
42
- app = FastAPI(title="Gemini Proxy API")
43
 
44
  @app.get("/")
45
  def greet_json():
@@ -53,13 +52,13 @@ async def health_check():
53
 
54
  @app.api_route("/v1/{protocol}/{host}/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
55
  # @app.api_route("/v1/{protocol}/{host}/{path:path}", methods=["POST"])
56
- async def proxy_gemini(request: Request, protocol: ProtocolType, host:str, path: str, proxy_api_key: str = Depends(verify_proxy_api_key)): # 添加代理认证依赖
57
  real_url = f"{protocol.value}://{host}/{path}"
58
  # 提取客户端请求的headers和body
59
  client_headers = dict(request.headers)
60
  client_body = await request.body()
61
 
62
- # 移除FastAPI自带的Host头,避免Gemini校验报错
63
  client_headers.pop("host", None)
64
  client_headers.pop("authorization", None)
65
 
 
9
  from dotenv import load_dotenv
10
  from enum import Enum
11
  from proxy import do_proxy
 
12
 
13
  # 配置日志
14
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 
38
  )
39
  return credentials.credentials
40
 
41
+ app = FastAPI(title="Common Proxy API")
42
 
43
  @app.get("/")
44
  def greet_json():
 
52
 
53
  @app.api_route("/v1/{protocol}/{host}/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
54
  # @app.api_route("/v1/{protocol}/{host}/{path:path}", methods=["POST"])
55
+ async def proxy(request: Request, protocol: ProtocolType, host:str, path: str, proxy_api_key: str = Depends(verify_proxy_api_key)): # 添加代理认证依赖
56
  real_url = f"{protocol.value}://{host}/{path}"
57
  # 提取客户端请求的headers和body
58
  client_headers = dict(request.headers)
59
  client_body = await request.body()
60
 
61
+ # 移除FastAPI自带的Host头,避免目标网站校验报错
62
  client_headers.pop("host", None)
63
  client_headers.pop("authorization", None)
64
 
memory-bank/activeContext.md CHANGED
@@ -1,33 +1,33 @@
1
- # Active Context
2
 
3
- ## Current work focus
4
- The current focus is on refining the existing codebase and improving its robustness and maintainability.
5
 
6
- ## Recent changes
7
- - Created the `memory-bank` directory and all core documentation files.
8
- - Reviewed `app.py`, `proxy.py`, `api_key_sb.py`, `requirements.txt`, and `.env`.
9
- - Removed the unnecessary call to `update_api_key_ran_at` from `api_key_sb.py`'s `get_api_key_info` function.
10
- - Removed the redundant `finally` block in `proxy.py` for `httpx.AsyncClient()`.
11
 
12
- ## Next steps
13
- - All `print` statements have been replaced with Python's `logging` module.
14
- - Consider a unified and structured error response format.
15
 
16
- ## Active decisions and considerations
17
- - Ensure the Memory Bank accurately reflects the current state and future direction of the project.
18
- - Prioritize understanding the existing codebase before proposing new changes.
19
 
20
- ## Learnings and project insights
21
- - The project is a FastAPI application acting as a reverse proxy.
22
- - It uses `httpx` for asynchronous HTTP requests.
23
- - API key management is handled via Supabase, with `api_key_sb.py` providing functions to fetch and update API key information.
24
- - The proxy implements retry logic with exponential backoff for `429 Too Many Requests` errors and updates the `ran_at` timestamp for API keys.
25
- - Environment variables (`PROXY_API_KEY`, `SUPABASE_URL`, `SUPABASE_KEY`) are loaded from `.env` using `python-dotenv`.
26
- - Dependencies are managed via `requirements.txt`.
27
 
28
- ## Important patterns and preferences
29
- - Adherence to the specified Memory Bank structure and content guidelines.
30
 
31
- ## Learnings and project insights
32
- - The project appears to be a Python-based FastAPI application, likely serving as a reverse proxy.
33
- - There's an existing `conda` environment setup.
 
1
+ # 当前上下文
2
 
3
+ ## 当前工作重点
4
+ 当前重点是完善现有代码库,提高其健壮性和可维护性。
5
 
6
+ ## 最近更改
7
+ - 创建了 `memory-bank` 目录和所有核心文档文件。
8
+ - 审查了 `app.py`、`proxy.py`、`api_key_sb.py`、`requirements.txt` `.env`。
9
+ - `api_key_sb.py` `get_api_key_info` 函数中删除了对 `update_api_key_ran_at` 的不必要调用。
10
+ - 删除了 `proxy.py` `httpx.AsyncClient()` 的冗余 `finally` 块。
11
 
12
+ ## 后续步骤
13
+ - 所有 `print` 语句都已替换为 Python `logging` 模块。
14
+ - 考虑统一且结构化的错误响应格式。
15
 
16
+ ## 当前决策和考虑
17
+ - 确保内存库准确反映项目的当前状态和未来方向。
18
+ - 在提出新更改之前,优先理解现有代码库。
19
 
20
+ ## 学习和项目洞察
21
+ - 该项目是一个充当反向代理的 FastAPI 应用程序。
22
+ - 它使用 `httpx` 进行异步 HTTP 请求。
23
+ - API 密钥管理通过 Supabase 处理,`api_key_sb.py` 提供获取和更新 API 密钥信息的函数。
24
+ - 代理实现了指数退避的重试逻辑,用于处理 `429 Too Many Requests` 错误,并更新 API 密钥的 `ran_at` 时间戳。
25
+ - 环境变量(`PROXY_API_KEY`、`SUPABASE_URL`、`SUPABASE_KEY`)使用 `python-dotenv` `.env` 加载。
26
+ - 依赖项通过 `requirements.txt` 管理。
27
 
28
+ ## 重要模式和偏好
29
+ - 遵守指定的内存库结构和内容指南。
30
 
31
+ ## 学习和项目洞察
32
+ - 该项目似乎是一个基于 Python FastAPI 应用程序,可能用作反向代理。
33
+ - 存在一个现有的 `conda` 环境设置。
memory-bank/productContext.md CHANGED
@@ -1,18 +1,18 @@
1
- # Product Context
2
 
3
- ## Why this project exists
4
- The "superproxy-1" project aims to address the need for a centralized and controlled access point to various backend APIs. This helps in managing API keys, enforcing rate limits, and providing a consistent interface for client applications.
5
 
6
- ## Problems it solves
7
- - **API Key Management:** Centralizes API key storage and usage, reducing the risk of exposure in client-side code.
8
- - **Rate Limiting:** Allows for global or per-client rate limiting to prevent abuse and ensure fair usage of backend services.
9
- - **Security:** Adds an additional layer of security by obscuring direct access to backend services.
10
- - **Simplified Integration:** Provides a single endpoint for multiple APIs, simplifying client-side integration.
11
 
12
- ## How it should work
13
- The proxy should receive incoming requests, validate them (e.g., check for valid API keys, apply rate limits), forward them to the appropriate backend API, and return the response to the client.
14
 
15
- ## User experience goals
16
- - **Reliability:** Ensure high availability and minimal latency for API requests.
17
- - **Ease of Use:** Provide clear documentation and a straightforward integration process for developers.
18
- - **Security:** Maintain a secure environment for API interactions.
 
1
+ # 产品上下文
2
 
3
+ ## 项目存在的理由
4
+ "superproxy-1" 项目旨在解决对各种后端 API 进行集中和受控访问的需求。这有助于管理 API 密钥、强制执行速率限制,并为客户端应用程序提供一致的接口。
5
 
6
+ ## 解决的问题
7
+ - **API 密钥管理:** 集中 API 密钥的存储和使用,降低客户端代码中暴露的风险。
8
+ - **速率限制:** 允许全局或按客户端进行速率限制,以防止滥用并确保后端服务的公平使用。
9
+ - **安全性:** 通过模糊对后端服务的直接访问,增加额外的安全层。
10
+ - **简化集成:** 为多个 API 提供单一端点,简化客户端集成。
11
 
12
+ ## 工作方式
13
+ 代理应接收传入请求,对其进行验证(例如,检查有效的 API 密钥,应用速率限制),将其转发到适当的后端 API,并将响应返回给客户端。
14
 
15
+ ## 用户体验目标
16
+ - **可靠性:** 确保 API 请求的高可用性和最小延迟。
17
+ - **易用性:** 为开发人员提供清晰的文档和直接的集成过程。
18
+ - **安全性:** API 交互维护一个安全的环境。
memory-bank/progress.md CHANGED
@@ -1,22 +1,22 @@
1
- # Progress
2
 
3
- ## What works
4
- - The foundational Memory Bank structure has been established with core documentation files.
5
- - Removed redundant `finally` block in `proxy.py` for `httpx.AsyncClient()`.
6
 
7
- ## What's left to build
8
- - All `print` statements have been replaced with Python's `logging` module.
9
- - Consider a unified and structured error response format.
10
- - Deployment strategy (Docker setup).
11
 
12
- ## Current status
13
- - Initial setup of project documentation is complete.
14
- - The project's core purpose and technical stack are outlined.
15
- - Redundant `finally` block in `proxy.py` has been successfully removed.
16
 
17
- ## Known issues
18
- - No specific issues identified yet, as core development has not begun.
19
 
20
- ## Evolution of project decisions
21
- - The decision to use FastAPI and `httpx` for asynchronous proxying is based on performance and ease of development.
22
- - The Memory Bank structure is adopted to ensure consistent and comprehensive project documentation.
 
1
+ # 进度
2
 
3
+ ## 已完成的工作
4
+ - 建立了包含核心文档文件的基础内存库结构。
5
+ - 删除了 `proxy.py` `httpx.AsyncClient()` 的冗余 `finally` 块。
6
 
7
+ ## 待完成的工作
8
+ - 所有 `print` 语句都已替换为 Python `logging` 模块。
9
+ - 考虑统一且结构化的错误响应格式。
10
+ - 部署策略(Docker 设置)。
11
 
12
+ ## 当前状态
13
+ - 项目文档的初始设置已完成。
14
+ - 项目的核心目的和技术栈已概述。
15
+ - `proxy.py` 中冗余的 `finally` 块已成功删除。
16
 
17
+ ## 已知问题
18
+ - 尚未发现具体问题,因为核心开发尚未开始。
19
 
20
+ ## 项目决策的演变
21
+ - 使用 FastAPI `httpx` 进行异步代理的决定是基于性能和开发便利性。
22
+ - 采用内存库结构是为了确保项目文档的一致性和全面性。
memory-bank/projectBrief.md CHANGED
@@ -1,14 +1,14 @@
1
- # Project Brief
2
 
3
- This project, "superproxy-1", is a proxy service designed to handle API requests. The primary goal is to provide a flexible and robust proxy layer for various applications.
4
 
5
- ## Core Requirements
6
- - Act as an intermediary for API requests.
7
- - Potentially handle authentication and authorization.
8
- - Provide logging and monitoring capabilities.
9
- - Be easily deployable and scalable.
10
 
11
- ## Goals
12
- - Enhance security by abstracting direct API access.
13
- - Improve performance through caching or load balancing (future consideration).
14
- - Simplify API integration for client applications.
 
1
+ # 项目简介
2
 
3
+ 本项目“superproxy-1”是一个旨在处理 API 请求的代理服务。主要目标是为各种应用程序提供一个灵活且健壮的代理层。
4
 
5
+ ## 核心要求
6
+ - 作为 API 请求的中介。
7
+ - 潜在地处理身份验证和授权。
8
+ - 提供日志和监控功能。
9
+ - 易于部署和扩展。
10
 
11
+ ## 目标
12
+ - 通过抽象直接的 API 访问来增强安全性。
13
+ - 通过缓存或负载均衡(未来考虑)来提高性能。
14
+ - 简化客户端应用程序的 API 集成。
memory-bank/systemPatterns.md CHANGED
@@ -1,23 +1,23 @@
1
- # System Patterns
2
 
3
- ## System Architecture
4
- The "superproxy-1" is designed as a lightweight, API-gateway-like service. It will primarily function as a reverse proxy, forwarding requests to various upstream services based on defined rules.
5
 
6
- ## Key Technical Decisions
7
- - **Asynchronous Processing:** Utilize an asynchronous framework (e.g., FastAPI with Uvicorn) to handle concurrent requests efficiently.
8
- - **Configuration-driven Routing:** Implement a flexible routing mechanism that can be configured to direct requests to different backend services.
9
- - **Modular Design:** Keep the core proxy logic separate from authentication, logging, and other cross-cutting concerns to promote maintainability and extensibility.
10
 
11
- ## Design Patterns in Use
12
- - **Proxy Pattern:** The core of the service, acting as a surrogate for other objects (backend APIs).
13
- - **Middleware Pattern:** For handling concerns like authentication, logging, and rate limiting before or after the main request processing.
14
 
15
- ## Component Relationships
16
- - **Client Applications:** Interact with the proxy service.
17
- - **Proxy Service:** Receives requests, processes them, and forwards them to Upstream Services.
18
- - **Upstream Services (Backend APIs):** The actual APIs that the proxy communicates with.
19
 
20
- ## Critical Implementation Paths
21
- - **Request Routing:** Efficiently determine the correct upstream service for an incoming request.
22
- - **Error Handling:** Gracefully handle errors from upstream services and communicate them effectively to clients.
23
- - **Security Measures:** Implement robust authentication and authorization mechanisms.
 
1
+ # 系统模式
2
 
3
+ ## 系统架构
4
+ superproxy-1”被设计为一个轻量级的、类似 API 网关的服务。它将主要作为反向代理,根据定义的规则将请求转发到各种上游服务。
5
 
6
+ ## 关键技术决策
7
+ - **异步处理:** 利用异步框架(例如,带有 Uvicorn FastAPI)高效处理并发请求。
8
+ - **配置驱动路由:** 实现一个灵活的路由机制,可以配置以将请求定向到不同的后端服务。
9
+ - **模块化设计:** 将核心代理逻辑与身份验证、日志记录和其他横切关注点分离,以提高可维护性和可扩展性。
10
 
11
+ ## 使用中的设计模式
12
+ - **代理模式:** 服务的核心,充当其他对象(后端 API)的替代品。
13
+ - **中间件模式:** 用于在主请求处理之前或之后处理身份验证、日志记录和速率限制等关注点。
14
 
15
+ ## 组件关系
16
+ - **客户端应用程序:** 与代理服务交互。
17
+ - **代理服务:** 接收请求,处理它们,并将它们转发到上游服务。
18
+ - **上游服务(后端 API):** 代理与之通信的实际 API。
19
 
20
+ ## 关键实现路径
21
+ - **请求路由:** 有效确定传入请求的正确上游服务。
22
+ - **错误处理:** 优雅地处理来自上游服务的错误,并有效地将其传达给客户端。
23
+ - **安全措施:** 实施强大的身份验证和授权机制。
memory-bank/techContext.md CHANGED
@@ -1,28 +1,28 @@
1
- # Tech Context
2
 
3
- ## Technologies Used
4
- - **Python:** Primary programming language.
5
- - **FastAPI:** Web framework for building the API.
6
- - **Uvicorn:** ASGI server for running FastAPI applications.
7
- - **`httpx`:** Asynchronous HTTP client for forwarding requests to upstream services.
8
- - **`python-dotenv`:** For managing environment variables.
9
 
10
- ## Development Setup
11
- - **Conda Environment:** The project uses a `conda` environment named `airs` for dependency management.
12
- - **`requirements.txt`:** Specifies Python dependencies.
13
- - **Docker:** For containerization and deployment.
14
 
15
- ## Technical Constraints
16
- - **Performance:** The proxy should be able to handle a high volume of concurrent requests with low latency.
17
- - **Security:** All sensitive information (e.g., API keys) must be handled securely, preferably through environment variables.
18
- - **Scalability:** The architecture should support horizontal scaling to accommodate increased load.
19
 
20
- ## Dependencies
21
  - `fastapi`
22
  - `uvicorn`
23
  - `httpx`
24
  - `python-dotenv`
25
 
26
- ## Tool Usage Patterns
27
- - **`uvicorn app:app --host 0.0.0.0 --port 7860 --reload`:** Command for local development server.
28
- - **`conda activate airs`:** To activate the development environment.
 
1
+ # 技术上下文
2
 
3
+ ## 使用的技术
4
+ - **Python:** 主要编程语言。
5
+ - **FastAPI:** 用于构建 API Web 框架。
6
+ - **Uvicorn:** 用于运行 FastAPI 应用程序的 ASGI 服务器。
7
+ - **`httpx`:** 用于将请求转发到上游服务的异步 HTTP 客户端。
8
+ - **`python-dotenv`:** 用于管理环境变量。
9
 
10
+ ## 开发设置
11
+ - **Conda 环境:** 项目使用名为 `airs` `conda` 环境进行依赖管理。
12
+ - **`requirements.txt`:** 指定 Python 依赖项。
13
+ - **Docker:** 用于容器化和部署。
14
 
15
+ ## 技术限制
16
+ - **性能:** 代理应能够以低延迟处理大量并发请求。
17
+ - **安全性:** 所有敏感信息(例如 API 密钥)必须安全处理,最好通过环境变量。
18
+ - **可扩展性:** 架构应支持水平扩展以适应增加的负载。
19
 
20
+ ## 依赖项
21
  - `fastapi`
22
  - `uvicorn`
23
  - `httpx`
24
  - `python-dotenv`
25
 
26
+ ## 工具使用模式
27
+ - **`uvicorn app:app --host 0.0.0.0 --port 7860 --reload`:** 用于本地开发服务器的命令。
28
+ - **`conda activate airs`:** 激活开发环境。
proxy.py CHANGED
@@ -20,6 +20,7 @@ async def do_proxy(url: str, method: str, headers: dict, content: str, max_retri
20
  try:
21
  async with httpx.AsyncClient() as client:
22
  for attempt in range(max_retries):
 
23
 
24
  # 获取API密钥信息
25
  api_key_info = await get_api_key_info('gemini-2.5-flash')
 
20
  try:
21
  async with httpx.AsyncClient() as client:
22
  for attempt in range(max_retries):
23
+ print('content',content)
24
 
25
  # 获取API密钥信息
26
  api_key_info = await get_api_key_info('gemini-2.5-flash')