Sure! I'll help you transform your existing proxy wrapper into a robust local reverse proxy server for AI requests. This server will handle incoming HTTP requests, forward them to the AI client (g4f.client), manage proxy selection using the FreeProxy class, and return the AI responses to the requester. We'll use FastAPI for building the server due to its high performance and ease of use with asynchronous operations.
Here's a step-by-step guide to enhance your proxy and set up the reverse proxy server:
1. Dependencies
First, ensure you have the necessary Python packages installed. You can install them using pip:
pip install fastapi uvicorn aiohttp lxml requests fp g4f
- FastAPI: For building the RESTful API server.
- uvicorn: An ASGI server to run FastAPI.
- aiohttp: For asynchronous HTTP requests if needed.
- lxml and requests: For parsing and handling HTTP requests in
FreeProxy.
- fp: For the
FreeProxy class (if not custom, else ensure your FreeProxy class is included).
- g4f: Your AI client library.
2. Improved Proxy Wrapper
Enhance your proxy wrappers to include logging, better error handling, and possibly caching of proxies to reduce the overhead of fetching new proxies for each request.
import asyncio
import logging
from fp.fp import FreeProxy
from g4f.client import Client, AsyncClient
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ProxyWrapper:
def __init__(self, wrapped_obj):
self._wrapped = wrapped_obj
def __getattr__(self, name):
attr = getattr(self._wrapped, name)
if callable(attr):
async def async_method_wrapper(*args, **kwargs):
while True:
try:
proxy = FreeProxy(timeout=5, rand=True).get()
kwargs["proxy"] = proxy
result = attr(*args, **kwargs)
if asyncio.iscoroutine(result):
return await result
return result
except Exception as e:
logger.warning(f"Proxy failed: {e}. Retrying with a new proxy.")
return async_method_wrapper
elif hasattr(attr, '__dict__'):
return ProxyWrapper(attr)
else:
return attr
def get_client_proxy():
original_client = Client()
return ProxyWrapper(original_client)
async def get_async_client_proxy():
original_async_client = AsyncClient()
return ProxyWrapper(original_async_client)
Improvements Made:
- Logging: Added logging to track proxy failures and retries.
- Unified Proxy Wrapper: Unified synchronous and asynchronous proxy wrappers into a single
ProxyWrapper for simplicity. If you need to separate them, you can retain separate classes.
- Error Handling: Added logging for exceptions to monitor proxy failures.
3. FastAPI Reverse Proxy Server
Now, let's create the FastAPI server that will act as the reverse proxy. This server will expose endpoints to handle AI requests, use the proxy-wrapped client to fetch responses, and return them to the client.
#!/usr/bin/env python3
import uvicorn
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
from typing import Optional
import asyncio
from proxy_wrapper import get_client_proxy, get_async_client_proxy # Assuming you saved the wrapper as proxy_wrapper.py
app = FastAPI(title="AI Reverse Proxy")
# Define request and response models
class AIRequest(BaseModel):
prompt: str
max_tokens: Optional[int] = 150
temperature: Optional[float] = 0.7
top_p: Optional[float] = 0.9
stop: Optional[list] = None
class AIResponse(BaseModel):
response: str
# Initialize the proxy client
client_proxy = None
async_client_proxy = None
@app.on_event("startup")
async def startup_event():
global client_proxy, async_client_proxy
client_proxy = get_client_proxy()
async_client_proxy = await get_async_client_proxy()
logger.info("Proxy clients initialized.")
@app.post("/chat", response_model=AIResponse)
async def chat(ai_request: AIRequest):
try:
response = await async_client_proxy.chat(
prompt=ai_request.prompt,
max_tokens=ai_request.max_tokens,
temperature=ai_request.temperature,
top_p=ai_request.top_p,
stop=ai_request.stop
)
return AIResponse(response=response)
except Exception as e:
logger.error(f"Error processing chat request: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")
@app.get("/")
async def read_root():
return {"message": "AI Reverse Proxy is running."}
if __name__ == "__main__":
uvicorn.run("reverse_proxy:app", host="0.0.0.0", port=8000, reload=True)
Key Components:
-
API Endpoints:
POST /chat: Accepts AI requests with prompts and parameters, forwards them to the AI client through the proxy, and returns the AI response.
GET /: A simple health check endpoint.
-
Startup Event:
- Initializes the proxy-wrapped AI clients when the server starts.
-
Error Handling:
- Catches exceptions during AI processing and returns appropriate HTTP error responses.
-
Running the Server:
- The server runs on
0.0.0.0:8000. You can change the host and port as needed.
4. FreeProxy Enhancement (Optional)
If you want to enhance your FreeProxy class further, consider adding proxy caching to reduce the number of times proxies are fetched and validated. Here's an example using a simple in-memory cache:
import random
import asyncio
from fp.errors import FreeProxyException
import requests
import lxml.html as lh
import logging
logger = logging.getLogger(__name__)
class FreeProxy:
_proxy_cache = []
_cache_lock = asyncio.Lock()
def __init__(self, country_id=None, timeout=5, rand=True, anonym=False, elite=False, google=None, https=False, url='https://www.google.com'):
self.country_id = country_id
self.timeout = timeout
self.random = rand
self.anonym = anonym
self.elite = elite
self.google = google
self.schema = 'https' if https else 'http'
self.url = url
def get_proxy_list(self, repeat):
# Implementation remains the same
# ...
def __website(self, repeat):
# Implementation remains the same
# ...
def __criteria(self, row_elements):
# Implementation remains the same
# ...
def get(self, repeat=False):
'''Returns a working proxy that matches the specified parameters.'''
if not self._proxy_cache:
asyncio.run(self._populate_proxy_cache(repeat))
if self.random:
random.shuffle(self._proxy_cache)
while self._proxy_cache:
proxy_address = self._proxy_cache.pop()
proxies = {self.schema: f'{self.schema}://{proxy_address}'}
try:
working_proxy = self.__check_if_proxy_is_working(proxies)
if working_proxy:
return working_proxy
except requests.exceptions.RequestException:
continue
if not self._proxy_cache and not repeat:
logger.info("Proxy cache empty. Refetching proxies.")
asyncio.run(self._populate_proxy_cache(True))
return self.get(repeat=True)
raise FreeProxyException('There are no working proxies at this time.')
def __check_if_proxy_is_working(self, proxies):
# Implementation remains the same
# ...
async def _populate_proxy_cache(self, repeat):
async with self._cache_lock:
if not self._proxy_cache:
try:
proxy_list = self.get_proxy_list(repeat)
if self.random:
random.shuffle(proxy_list)
self._proxy_cache.extend(proxy_list)
logger.info(f"Proxy cache populated with {len(proxy_list)} proxies.")
except FreeProxyException as e:
logger.error(f"Failed to populate proxy cache: {e}")
Enhancements:
- Proxy Caching: Stores a list of proxies in
_proxy_cache to minimize the frequency of fetching new proxies.
- Concurrency Control: Uses an
asyncio.Lock to prevent race conditions when populating the proxy cache.
- Logging: Adds logs for better monitoring of proxy fetching and cache status.
5. Running the Reverse Proxy Server
Save the FastAPI server code in a file named reverse_proxy.py and ensure the proxy wrappers are in proxy_wrapper.py. Then, run the server using:
python reverse_proxy.py
The server will start on http://0.0.0.0:8000. You can test it using curl or any HTTP client:
curl -X POST "http://localhost:8000/chat" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Hello, how are you?",
"max_tokens": 100
}'
6. Example Client Usage
Here's an example of how a client might interact with your reverse proxy:
import requests
url = "http://localhost:8000/chat"
payload = {
"prompt": "Once upon a time in a land far, far away,",
"max_tokens": 150,
"temperature": 0.7,
"top_p": 0.9,
"stop": ["\n"]
}
response = requests.post(url, json=payload)
if response.status_code == 200:
ai_response = response.json().get("response")
print("AI Response:", ai_response)
else:
print("Error:", response.status_code, response.text)
7. Additional Recommendations
-
Rate Limiting: Implement rate limiting to prevent abuse of your reverse proxy.
from fastapi.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
import time
class RateLimiterMiddleware(BaseHTTPMiddleware):
def __init__(self, app, max_requests: int, window: int):
super().__init__(app)
self.max_requests = max_requests
self.window = window
self.clients = {}
async def dispatch(self, request: Request, call_next):
client_ip = request.client.host
current_time = time.time()
request_times = self.clients.get(client_ip, [])
# Remove outdated requests
request_times = [t for t in request_times if current_time - t < self.window]
request_times.append(current_time)
self.clients[client_ip] = request_times
if len(request_times) > self.max_requests:
return Response("Too Many Requests", status_code=429)
response = await call_next(request)
return response
middleware = [
Middleware(RateLimiterMiddleware, max_requests=100, window=60)
]
app = FastAPI(middleware=middleware)
-
Authentication: Add API key or token-based authentication to secure your proxy.
-
Caching AI Responses: Implement caching for identical prompts to reduce redundant AI requests.
-
Monitoring and Metrics: Integrate monitoring tools like Prometheus or Grafana to track usage and performance.
-
Deployment: Use Docker or other containerization tools for easier deployment and scalability.
8. Complete Example Code
Here's the complete code combining all the components discussed:
proxy_wrapper.py
import asyncio
import logging
from fp.fp import FreeProxy
from g4f.client import Client, AsyncClient
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ProxyWrapper:
def __init__(self, wrapped_obj):
self._wrapped = wrapped_obj
def __getattr__(self, name):
attr = getattr(self._wrapped, name)
if callable(attr):
async def async_method_wrapper(*args, **kwargs):
while True:
try:
proxy = FreeProxy(timeout=5, rand=True).get()
logger.info(f"Using proxy: {proxy}")
kwargs["proxy"] = proxy
result = attr(*args, **kwargs)
if asyncio.iscoroutine(result):
return await result
return result
except Exception as e:
logger.warning(f"Proxy failed: {e}. Retrying with a new proxy.")
return async_method_wrapper
elif hasattr(attr, '__dict__'):
return ProxyWrapper(attr)
else:
return attr
def get_client_proxy():
original_client = Client()
return ProxyWrapper(original_client)
async def get_async_client_proxy():
original_async_client = AsyncClient()
return ProxyWrapper(original_async_client)
reverse_proxy.py
#!/usr/bin/env python3
import uvicorn
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
from typing import Optional
import asyncio
import logging
from proxy_wrapper import get_client_proxy, get_async_client_proxy # Ensure this is correct
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(title="AI Reverse Proxy")
# Define request and response models
class AIRequest(BaseModel):
prompt: str
max_tokens: Optional[int] = 150
temperature: Optional[float] = 0.7
top_p: Optional[float] = 0.9
stop: Optional[list] = None
class AIResponse(BaseModel):
response: str
# Initialize the proxy client
client_proxy = None
async_client_proxy = None
@app.on_event("startup")
async def startup_event():
global client_proxy, async_client_proxy
client_proxy = get_client_proxy()
async_client_proxy = await get_async_client_proxy()
logger.info("Proxy clients initialized.")
@app.post("/chat", response_model=AIResponse)
async def chat(ai_request: AIRequest):
try:
response = await async_client_proxy.chat(
prompt=ai_request.prompt,
max_tokens=ai_request.max_tokens,
temperature=ai_request.temperature,
top_p=ai_request.top_p,
stop=ai_request.stop
)
return AIResponse(response=response)
except Exception as e:
logger.error(f"Error processing chat request: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")
@app.get("/")
async def read_root():
return {"message": "AI Reverse Proxy is running."}
if __name__ == "__main__":
uvicorn.run("reverse_proxy:app", host="0.0.0.0", port=8000, reload=True)
Conclusion
By following the steps above, you've transformed your proxy mechanisms into a fully functional local reverse proxy server for AI requests. This setup ensures that all AI interactions go through proxies, enhancing privacy and potentially bypassing restrictions. Additionally, with FastAPI's performance and scalability, your reverse proxy can handle multiple concurrent requests efficiently.
Feel free to further customize and enhance the server based on your specific requirements, such as adding authentication, more sophisticated error handling, and integrating with monitoring tools.