To transform your existing proxy wrapper into a fully functional local reverse-proxy server for requesting AI responses, we'll integrate the proxy logic with a web framework. This will allow clients to send HTTP requests to your local server, which will then handle fetching AI responses through different proxies.
Here's a step-by-step guide to enhancing your proxy setup into a local reverse-proxy server:
-
Project Structure
ai_reverse_proxy/
├── main.py
├── proxy_wrapper.py
├── free_proxy.py
├── requirements.txt
└── README.md
-
Setup and Installation
requirements.txt
fastapi
uvicorn
requests
lxml
g4f
Install the dependencies using pip:
pip install -r requirements.txt
-
Proxy Handling Logic
free_proxy.py
This module contains the FreeProxy class for fetching and validating free proxies.
# free_proxy.py
import random
import lxml.html as lh
import requests
from requests.exceptions import RequestException
class FreeProxyException(Exception):
pass
class FreeProxy:
"""
FreeProxy class scrapes proxies from various sources and validates them.
"""
def __init__(self, country_id=None, timeout=5, rand=False, 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):
try:
page = requests.get(self.__website(repeat), timeout=self.timeout)
doc = lh.fromstring(page.content)
except RequestException as e:
raise FreeProxyException(f'Request to {self.__website(repeat)} failed') from e
try:
tr_elements = doc.xpath('//*[@id="list"]//tr')
proxies = [
f"{tr[0].text_content()}:{tr[1].text_content()}"
for tr in tr_elements[1:]
if self.__criteria(tr)
]
return proxies
except Exception as e:
raise FreeProxyException('Failed to get list of proxies') from e
def __website(self, repeat):
if repeat:
return "https://free-proxy-list.net"
elif self.country_id == ['US']:
return 'https://www.us-proxy.org'
elif self.country_id == ['GB']:
return 'https://free-proxy-list.net/uk-proxy.html'
else:
return 'https://www.sslproxies.org'
def __criteria(self, row):
country = not self.country_id or row[2].text_content() in self.country_id
elite = not self.elite or 'elite proxy' in row[4].text_content().lower()
anonym = not self.anonym or 'anonymous' in row[4].text_content().lower()
google = self.google is None or self.google == (row[5].text_content().lower() == 'yes')
https = row[6].text_content().lower() == 'yes' if self.schema == 'https' else True
return country and elite and anonym and google and https
def get(self, repeat=False):
"""
Returns a working proxy that matches the specified parameters.
"""
proxy_list = self.get_proxy_list(repeat)
if self.random:
random.shuffle(proxy_list)
for proxy_address in proxy_list:
proxies = {self.schema: f"{self.schema}://{proxy_address}"}
if self.__check_if_proxy_is_working(proxies):
return proxies[self.schema]
if not repeat:
# Retry with different sources
self.country_id = None
return self.get(repeat=True)
raise FreeProxyException('There are no working proxies at this time.')
def __check_if_proxy_is_working(self, proxies):
try:
with requests.get(self.url, proxies=proxies, timeout=self.timeout) as response:
if response.status_code == 200:
return proxies[self.schema]
except RequestException:
return False
proxy_wrapper.py
This module wraps around the AI client to handle proxy rotation both synchronously and asynchronously.
# proxy_wrapper.py
import asyncio
from fp.free_proxy import FreeProxy, FreeProxyException
from g4f.client import Client, AsyncClient
class ProxyWrapper:
def __init__(self, wrapped_obj, proxy_params=None):
self._wrapped = wrapped_obj
self.proxy_params = proxy_params or {}
def __getattr__(self, name):
attr = getattr(self._wrapped, name)
if callable(attr):
def method_wrapper(*args, **kwargs):
kwargs.update(self.proxy_params)
while True:
try:
proxy = FreeProxy(**self.proxy_params).get()
kwargs["proxy"] = proxy
return attr(*args, **kwargs)
except FreeProxyException:
continue
except Exception as e:
raise e
return method_wrapper
elif hasattr(attr, '__dict__'):
return ProxyWrapper(attr, self.proxy_params)
else:
return attr
class AsyncProxyWrapper:
def __init__(self, wrapped_obj, proxy_params=None):
self._wrapped = wrapped_obj
self.proxy_params = proxy_params or {}
self._loop = asyncio.get_event_loop()
def __getattr__(self, name):
attr = getattr(self._wrapped, name)
if callable(attr):
async def method_wrapper(*args, **kwargs):
kwargs.update(self.proxy_params)
while True:
try:
proxy = await self._loop.run_in_executor(
None,
lambda: FreeProxy(**self.proxy_params).get()
)
kwargs["proxy"] = proxy
result = attr(*args, **kwargs)
if asyncio.iscoroutine(result):
return await result
return result
except FreeProxyException:
continue
except Exception as e:
raise e
return method_wrapper
elif hasattr(attr, '__dict__'):
return AsyncProxyWrapper(attr, self.proxy_params)
else:
return attr
def get_client_proxy(proxy_params=None):
original_client = Client()
return ProxyWrapper(original_client, proxy_params)
async def get_async_client_proxy(proxy_params=None):
original_async_client = AsyncClient()
return AsyncProxyWrapper(original_async_client, proxy_params)
-
Building the Reverse Proxy Server
main.py
This is the primary entry point for the reverse-proxy server. It sets up the API endpoints and integrates the proxy wrappers.
# main.py
import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
import asyncio
from proxy_wrapper import get_client_proxy, get_async_client_proxy
from fp.free_proxy import FreeProxyException
app = FastAPI(
title="AI Reverse Proxy",
description="A local reverse-proxy server for requesting AI responses through rotating proxies.",
version="1.0.0",
)
# Configuration for FreeProxy
PROXY_CONFIG = {
'country_id': ['US', 'GB'], # Example countries
'timeout': 5,
'rand': True,
'anonym': True,
'elite': True,
'google': True,
'https': True,
'url': 'https://www.google.com'
}
class AIRequest(BaseModel):
prompt: str
model: str = "gpt-4"
temperature: float = 0.7
max_tokens: int = 150
@app.post("/ask")
async def ask_ai(request: AIRequest):
"""
Endpoint to get AI response based on the provided prompt.
"""
try:
async_client = await get_async_client_proxy(proxy_params=PROXY_CONFIG)
response = await async_client.ask(
prompt=request.prompt,
model=request.model,
temperature=request.temperature,
max_tokens=request.max_tokens
)
return JSONResponse(content={"response": response})
except FreeProxyException as e:
raise HTTPException(status_code=502, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/")
async def root():
return {"message": "AI Reverse Proxy is up and running."}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
-
Running the Server
Start the server using the following command:
python main.py
The server will be accessible at http://localhost:8000. You can interact with the API using tools like cURL, Postman, or via the automatically generated Swagger UI at http://localhost:8000/docs.
-
Usage Example
Request:
curl -X POST "http://localhost:8000/ask" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Explain the theory of relativity.",
"model": "gpt-4",
"temperature": 0.5,
"max_tokens": 200
}'
Response:
{
"response": "The theory of relativity, developed by Albert Einstein, comprises two interrelated theories: special relativity and general relativity. Special relativity addresses the physics of objects moving at constant speeds, particularly those approaching the speed of light, introducing concepts like time dilation and length contraction. It also established the equivalence of mass and energy, encapsulated in the famous equation E=mc². General relativity extends these principles to include gravity, describing it not as a force but as a curvature of spacetime caused by mass and energy. This curvature affects the motion of objects, causing phenomena such as the bending of light around massive objects and the expansion of the universe. The theory has been confirmed by numerous experiments and observations, fundamentally altering our understanding of space, time, and gravity."
}
-
Enhancements and Best Practices
-
Logging: Implement logging to monitor proxy usage, errors, and AI responses. Python's built-in logging module can be integrated into main.py and other modules.
-
Rate Limiting: Protect your proxy server from abuse by implementing rate limiting using packages like slowapi or fastapi-limiter.
-
Caching: To improve performance and reduce repeated AI requests for the same prompt, incorporate caching mechanisms using tools like Redis or in-memory caching with cachetools.
-
Security:
- Authentication: Secure your API endpoints with API keys or OAuth to prevent unauthorized access.
- Validation: Ensure all inputs are validated to prevent injection attacks or malformed requests.
-
Proxy Pool Management: Maintain a pool of working proxies to reduce latency caused by proxy fetching and validation. Implement periodic checks to refresh the proxy list.
-
Concurrency Handling: FastAPI and Uvicorn handle concurrency efficiently, but ensure that the proxy fetching logic doesn't become a bottleneck. Optimize the FreeProxy class for better performance, possibly by asynchronous proxy validation.
-
Complete Code Files
For your convenience, here are the complete code files consolidated.
free_proxy.py
import random
import lxml.html as lh
import requests
from requests.exceptions import RequestException
class FreeProxyException(Exception):
pass
class FreeProxy:
"""
FreeProxy class scrapes proxies from various sources and validates them.
"""
def __init__(self, country_id=None, timeout=5, rand=False, 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):
try:
page = requests.get(self.__website(repeat), timeout=self.timeout)
doc = lh.fromstring(page.content)
except RequestException as e:
raise FreeProxyException(f'Request to {self.__website(repeat)} failed') from e
try:
tr_elements = doc.xpath('//*[@id="list"]//tr')
proxies = [
f"{tr[0].text_content()}:{tr[1].text_content()}"
for tr in tr_elements[1:]
if self.__criteria(tr)
]
return proxies
except Exception as e:
raise FreeProxyException('Failed to get list of proxies') from e
def __website(self, repeat):
if repeat:
return "https://free-proxy-list.net"
elif self.country_id == ['US']:
return 'https://www.us-proxy.org'
elif self.country_id == ['GB']:
return 'https://free-proxy-list.net/uk-proxy.html'
else:
return 'https://www.sslproxies.org'
def __criteria(self, row):
country = not self.country_id or row[2].text_content() in self.country_id
elite = not self.elite or 'elite proxy' in row[4].text_content().lower()
anonym = not self.anonym or 'anonymous' in row[4].text_content().lower()
google = self.google is None or self.google == (row[5].text_content().lower() == 'yes')
https = row[6].text_content().lower() == 'yes' if self.schema == 'https' else True
return country and elite and anonym and google and https
def get(self, repeat=False):
"""
Returns a working proxy that matches the specified parameters.
"""
proxy_list = self.get_proxy_list(repeat)
if self.random:
random.shuffle(proxy_list)
for proxy_address in proxy_list:
proxies = {self.schema: f"{self.schema}://{proxy_address}"}
if self.__check_if_proxy_is_working(proxies):
return proxies[self.schema]
if not repeat:
# Retry with different sources
self.country_id = None
return self.get(repeat=True)
raise FreeProxyException('There are no working proxies at this time.')
def __check_if_proxy_is_working(self, proxies):
try:
with requests.get(self.url, proxies=proxies, timeout=self.timeout) as response:
if response.status_code == 200:
return proxies[self.schema]
except RequestException:
return False
-
Conclusion
With this setup, you've successfully transformed your proxy wrapper into a robust local reverse-proxy server for AI responses. This server fetches AI responses using rotating proxies, enhancing privacy and potentially bypassing IP-related limitations. Remember to monitor the health of your proxies and consider incorporating additional features like authentication and rate limiting to secure and optimize your proxy server.