Spaces:
Running
Running
Deploy 7599004a
Browse files- .env.example +1 -0
- README.md +2 -0
- backend/integrations/cloudflare_transport.py +17 -12
- backend/integrations/llm_factory.py +5 -3
- tests/test_cloudflare_provider.py +21 -0
.env.example
CHANGED
|
@@ -17,6 +17,7 @@
|
|
| 17 |
# CLOUDFLARE_ACCOUNT_ID=your_account_id
|
| 18 |
# CLOUDFLARE_API_TOKEN=your_workers_ai_token
|
| 19 |
# CLOUDFLARE_GATEWAY_ID=default # optional Cloudflare AI Gateway route
|
|
|
|
| 20 |
# CLOUDFLARE_MODEL=@cf/zai-org/glm-4.7-flash
|
| 21 |
# CLOUDFLARE_DAILY_REQUEST_LIMIT=50
|
| 22 |
# [REQUIRED - at least one] LLM API key for the AI reviewers.
|
|
|
|
| 17 |
# CLOUDFLARE_ACCOUNT_ID=your_account_id
|
| 18 |
# CLOUDFLARE_API_TOKEN=your_workers_ai_token
|
| 19 |
# CLOUDFLARE_GATEWAY_ID=default # optional Cloudflare AI Gateway route
|
| 20 |
+
# CLOUDFLARE_GATEWAY_TOKEN=your_ai_gateway_run_token # optional separate gateway auth token
|
| 21 |
# CLOUDFLARE_MODEL=@cf/zai-org/glm-4.7-flash
|
| 22 |
# CLOUDFLARE_DAILY_REQUEST_LIMIT=50
|
| 23 |
# [REQUIRED - at least one] LLM API key for the AI reviewers.
|
README.md
CHANGED
|
@@ -74,6 +74,8 @@ Set `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` to use Workers AI's `@cf/
|
|
| 74 |
|
| 75 |
When the direct Workers AI API is unreachable, set `CLOUDFLARE_GATEWAY_ID` to an AI Gateway ID (for example `default`) to route through Cloudflare AI Gateway. The app requests that gateway cache and stored logs be skipped. Gateway-level Logpush and account policies may still apply; review them before sending private code. Cloudflare's OpenAI-compatible gateway endpoint is marked deprecated, so this route should be migrated when Cloudflare provides a replacement reachable from the deployment environment.
|
| 76 |
|
|
|
|
|
|
|
| 77 |
Retrieval is optional. It uses ChromaDB with local embeddings when enabled; the hosted workflow can continue with the pull request diff when retrieval is disabled or unavailable. The index is selective and revision-aware, rather than a blind copy of every repository file.
|
| 78 |
|
| 79 |
## Try it locally
|
|
|
|
| 74 |
|
| 75 |
When the direct Workers AI API is unreachable, set `CLOUDFLARE_GATEWAY_ID` to an AI Gateway ID (for example `default`) to route through Cloudflare AI Gateway. The app requests that gateway cache and stored logs be skipped. Gateway-level Logpush and account policies may still apply; review them before sending private code. Cloudflare's OpenAI-compatible gateway endpoint is marked deprecated, so this route should be migrated when Cloudflare provides a replacement reachable from the deployment environment.
|
| 76 |
|
| 77 |
+
The gateway route can use a separate `CLOUDFLARE_GATEWAY_TOKEN`, sent only as the gateway authorization token; `CLOUDFLARE_API_TOKEN` remains the Workers AI provider credential. This is useful when the Workers AI token cannot also run requests through the gateway. Store both as deployment secrets, never in the repository. Cloudflare gateway Run permission can apply account-wide, so grant only the access you intend. A gateway's first-time creation and permissions may need to be completed in the Cloudflare dashboard.
|
| 78 |
+
|
| 79 |
Retrieval is optional. It uses ChromaDB with local embeddings when enabled; the hosted workflow can continue with the pull request diff when retrieval is disabled or unavailable. The index is selective and revision-aware, rather than a blind copy of every repository file.
|
| 80 |
|
| 81 |
## Try it locally
|
backend/integrations/cloudflare_transport.py
CHANGED
|
@@ -13,22 +13,25 @@ import httpx
|
|
| 13 |
|
| 14 |
|
| 15 |
HOST = "api.cloudflare.com"
|
|
|
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
| 18 |
|
| 19 |
class ReachableCloudflareRoutes:
|
| 20 |
"""Resolve normally and cache only addresses with a verified TLS handshake."""
|
| 21 |
|
| 22 |
-
def __init__(self):
|
|
|
|
|
|
|
|
|
|
| 23 |
self._lock = threading.Lock()
|
| 24 |
self._routes = []
|
| 25 |
self._expires = 0.0
|
| 26 |
|
| 27 |
-
|
| 28 |
-
def _probe(address):
|
| 29 |
try:
|
| 30 |
with socket.create_connection((address, 443), timeout=3) as conn:
|
| 31 |
-
with ssl.create_default_context().wrap_socket(conn, server_hostname=
|
| 32 |
return address
|
| 33 |
except OSError:
|
| 34 |
return None
|
|
@@ -39,7 +42,7 @@ class ReachableCloudflareRoutes:
|
|
| 39 |
routes = [item for item in self._routes if item not in excluded] if now < self._expires else []
|
| 40 |
if routes:
|
| 41 |
return routes[0]
|
| 42 |
-
addresses = list(dict.fromkeys(item[4][0] for item in socket.getaddrinfo(
|
| 43 |
addresses = [item for item in addresses if item not in excluded]
|
| 44 |
with ThreadPoolExecutor(max_workers=max(1, len(addresses))) as pool:
|
| 45 |
futures = [pool.submit(self._probe, address) for address in addresses]
|
|
@@ -56,13 +59,13 @@ class ReachableCloudflareRoutes:
|
|
| 56 |
self._routes = [route for route in self._routes if route != address]
|
| 57 |
|
| 58 |
|
| 59 |
-
def _routed_request(request, address):
|
| 60 |
-
if request.url.scheme != "https" or request.url.host !=
|
| 61 |
-
raise ValueError("Cloudflare transport only permits
|
| 62 |
headers = httpx.Headers(request.headers)
|
| 63 |
-
headers["Host"] =
|
| 64 |
extensions = dict(request.extensions)
|
| 65 |
-
extensions["sni_hostname"] =
|
| 66 |
return httpx.Request(request.method, request.url.copy_with(host=address), headers=headers,
|
| 67 |
stream=request.stream, extensions=extensions)
|
| 68 |
|
|
@@ -70,6 +73,7 @@ def _routed_request(request, address):
|
|
| 70 |
class CloudflareTransport(httpx.BaseTransport):
|
| 71 |
def __init__(self, routes):
|
| 72 |
self.routes = routes
|
|
|
|
| 73 |
self.transport = httpx.HTTPTransport(local_address="0.0.0.0", retries=0)
|
| 74 |
|
| 75 |
def handle_request(self, request):
|
|
@@ -83,7 +87,7 @@ class CloudflareTransport(httpx.BaseTransport):
|
|
| 83 |
time.sleep(2)
|
| 84 |
continue
|
| 85 |
try:
|
| 86 |
-
return self.transport.handle_request(_routed_request(request, address))
|
| 87 |
except (httpx.ConnectError, httpx.ConnectTimeout):
|
| 88 |
self.routes.invalidate(address)
|
| 89 |
excluded.append(address)
|
|
@@ -97,6 +101,7 @@ class CloudflareTransport(httpx.BaseTransport):
|
|
| 97 |
class AsyncCloudflareTransport(httpx.AsyncBaseTransport):
|
| 98 |
def __init__(self, routes):
|
| 99 |
self.routes = routes
|
|
|
|
| 100 |
self.transport = httpx.AsyncHTTPTransport(local_address="0.0.0.0", retries=0)
|
| 101 |
|
| 102 |
async def handle_async_request(self, request):
|
|
@@ -110,7 +115,7 @@ class AsyncCloudflareTransport(httpx.AsyncBaseTransport):
|
|
| 110 |
await asyncio.sleep(2)
|
| 111 |
continue
|
| 112 |
try:
|
| 113 |
-
return await self.transport.handle_async_request(_routed_request(request, address))
|
| 114 |
except (httpx.ConnectError, httpx.ConnectTimeout):
|
| 115 |
await asyncio.to_thread(self.routes.invalidate, address)
|
| 116 |
excluded.append(address)
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
HOST = "api.cloudflare.com"
|
| 16 |
+
ALLOWED_HOSTS = {HOST, "gateway.ai.cloudflare.com"}
|
| 17 |
logger = logging.getLogger(__name__)
|
| 18 |
|
| 19 |
|
| 20 |
class ReachableCloudflareRoutes:
|
| 21 |
"""Resolve normally and cache only addresses with a verified TLS handshake."""
|
| 22 |
|
| 23 |
+
def __init__(self, host=HOST):
|
| 24 |
+
if host not in ALLOWED_HOSTS:
|
| 25 |
+
raise ValueError("Cloudflare transport only permits official Cloudflare HTTPS hosts")
|
| 26 |
+
self.host = host
|
| 27 |
self._lock = threading.Lock()
|
| 28 |
self._routes = []
|
| 29 |
self._expires = 0.0
|
| 30 |
|
| 31 |
+
def _probe(self, address):
|
|
|
|
| 32 |
try:
|
| 33 |
with socket.create_connection((address, 443), timeout=3) as conn:
|
| 34 |
+
with ssl.create_default_context().wrap_socket(conn, server_hostname=self.host):
|
| 35 |
return address
|
| 36 |
except OSError:
|
| 37 |
return None
|
|
|
|
| 42 |
routes = [item for item in self._routes if item not in excluded] if now < self._expires else []
|
| 43 |
if routes:
|
| 44 |
return routes[0]
|
| 45 |
+
addresses = list(dict.fromkeys(item[4][0] for item in socket.getaddrinfo(self.host, 443, socket.AF_INET, socket.SOCK_STREAM)))[:12]
|
| 46 |
addresses = [item for item in addresses if item not in excluded]
|
| 47 |
with ThreadPoolExecutor(max_workers=max(1, len(addresses))) as pool:
|
| 48 |
futures = [pool.submit(self._probe, address) for address in addresses]
|
|
|
|
| 59 |
self._routes = [route for route in self._routes if route != address]
|
| 60 |
|
| 61 |
|
| 62 |
+
def _routed_request(request, address, host=HOST):
|
| 63 |
+
if host not in ALLOWED_HOSTS or request.url.scheme != "https" or request.url.host != host:
|
| 64 |
+
raise ValueError("Cloudflare transport only permits configured official HTTPS hosts")
|
| 65 |
headers = httpx.Headers(request.headers)
|
| 66 |
+
headers["Host"] = host
|
| 67 |
extensions = dict(request.extensions)
|
| 68 |
+
extensions["sni_hostname"] = host
|
| 69 |
return httpx.Request(request.method, request.url.copy_with(host=address), headers=headers,
|
| 70 |
stream=request.stream, extensions=extensions)
|
| 71 |
|
|
|
|
| 73 |
class CloudflareTransport(httpx.BaseTransport):
|
| 74 |
def __init__(self, routes):
|
| 75 |
self.routes = routes
|
| 76 |
+
self.host = getattr(routes, "host", HOST)
|
| 77 |
self.transport = httpx.HTTPTransport(local_address="0.0.0.0", retries=0)
|
| 78 |
|
| 79 |
def handle_request(self, request):
|
|
|
|
| 87 |
time.sleep(2)
|
| 88 |
continue
|
| 89 |
try:
|
| 90 |
+
return self.transport.handle_request(_routed_request(request, address, self.host))
|
| 91 |
except (httpx.ConnectError, httpx.ConnectTimeout):
|
| 92 |
self.routes.invalidate(address)
|
| 93 |
excluded.append(address)
|
|
|
|
| 101 |
class AsyncCloudflareTransport(httpx.AsyncBaseTransport):
|
| 102 |
def __init__(self, routes):
|
| 103 |
self.routes = routes
|
| 104 |
+
self.host = getattr(routes, "host", HOST)
|
| 105 |
self.transport = httpx.AsyncHTTPTransport(local_address="0.0.0.0", retries=0)
|
| 106 |
|
| 107 |
async def handle_async_request(self, request):
|
|
|
|
| 115 |
await asyncio.sleep(2)
|
| 116 |
continue
|
| 117 |
try:
|
| 118 |
+
return await self.transport.handle_async_request(_routed_request(request, address, self.host))
|
| 119 |
except (httpx.ConnectError, httpx.ConnectTimeout):
|
| 120 |
await asyncio.to_thread(self.routes.invalidate, address)
|
| 121 |
excluded.append(address)
|
backend/integrations/llm_factory.py
CHANGED
|
@@ -55,6 +55,7 @@ class CloudflareRateLimiter(BaseRateLimiter):
|
|
| 55 |
# a conservative application cap, not a measurement of Cloudflare neurons.
|
| 56 |
_cloudflare_limiter = CloudflareRateLimiter(max(1, int(os.getenv("CLOUDFLARE_DAILY_REQUEST_LIMIT", "50"))))
|
| 57 |
_cloudflare_routes = ReachableCloudflareRoutes()
|
|
|
|
| 58 |
DEFAULT_TEMPERATURE = 0.0
|
| 59 |
DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
|
| 60 |
DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
|
|
@@ -121,6 +122,7 @@ def _get_cloudflare_chat(**kwargs: Any) -> Optional[Any]:
|
|
| 121 |
api_key = os.environ.get("CLOUDFLARE_API_TOKEN", "").strip()
|
| 122 |
account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip()
|
| 123 |
gateway_id = os.environ.get("CLOUDFLARE_GATEWAY_ID", "").strip()
|
|
|
|
| 124 |
if not api_key or not account_id:
|
| 125 |
return None
|
| 126 |
if not re.fullmatch(r"[0-9a-fA-F]{32}", account_id):
|
|
@@ -139,10 +141,10 @@ def _get_cloudflare_chat(**kwargs: Any) -> Optional[Any]:
|
|
| 139 |
# Cloudflare's AI Gateway is an official alternate route to Workers AI.
|
| 140 |
# Request no gateway cache or stored logs for potentially private code.
|
| 141 |
headers = dict(kwargs.pop("default_headers", {}) or {})
|
| 142 |
-
headers.update({"cf-aig-authorization": f"Bearer {api_key}", "cf-aig-collect-log": "false", "cf-aig-skip-cache": "true"})
|
| 143 |
kwargs["default_headers"] = headers
|
| 144 |
-
kwargs.setdefault("http_client", httpx.Client(transport=
|
| 145 |
-
kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=
|
| 146 |
base_url = f"https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/compat"
|
| 147 |
else:
|
| 148 |
kwargs.setdefault("http_client", httpx.Client(transport=CloudflareTransport(_cloudflare_routes), timeout=timeout))
|
|
|
|
| 55 |
# a conservative application cap, not a measurement of Cloudflare neurons.
|
| 56 |
_cloudflare_limiter = CloudflareRateLimiter(max(1, int(os.getenv("CLOUDFLARE_DAILY_REQUEST_LIMIT", "50"))))
|
| 57 |
_cloudflare_routes = ReachableCloudflareRoutes()
|
| 58 |
+
_cloudflare_gateway_routes = ReachableCloudflareRoutes("gateway.ai.cloudflare.com")
|
| 59 |
DEFAULT_TEMPERATURE = 0.0
|
| 60 |
DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
|
| 61 |
DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
|
|
|
|
| 122 |
api_key = os.environ.get("CLOUDFLARE_API_TOKEN", "").strip()
|
| 123 |
account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip()
|
| 124 |
gateway_id = os.environ.get("CLOUDFLARE_GATEWAY_ID", "").strip()
|
| 125 |
+
gateway_token = os.environ.get("CLOUDFLARE_GATEWAY_TOKEN", "").strip()
|
| 126 |
if not api_key or not account_id:
|
| 127 |
return None
|
| 128 |
if not re.fullmatch(r"[0-9a-fA-F]{32}", account_id):
|
|
|
|
| 141 |
# Cloudflare's AI Gateway is an official alternate route to Workers AI.
|
| 142 |
# Request no gateway cache or stored logs for potentially private code.
|
| 143 |
headers = dict(kwargs.pop("default_headers", {}) or {})
|
| 144 |
+
headers.update({"cf-aig-authorization": f"Bearer {gateway_token or api_key}", "cf-aig-collect-log": "false", "cf-aig-skip-cache": "true"})
|
| 145 |
kwargs["default_headers"] = headers
|
| 146 |
+
kwargs.setdefault("http_client", httpx.Client(transport=CloudflareTransport(_cloudflare_gateway_routes), timeout=timeout))
|
| 147 |
+
kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=AsyncCloudflareTransport(_cloudflare_gateway_routes), timeout=timeout))
|
| 148 |
base_url = f"https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/compat"
|
| 149 |
else:
|
| 150 |
kwargs.setdefault("http_client", httpx.Client(transport=CloudflareTransport(_cloudflare_routes), timeout=timeout))
|
tests/test_cloudflare_provider.py
CHANGED
|
@@ -32,6 +32,16 @@ def test_gateway_uses_cloudflare_model_and_disables_cache_and_logs(monkeypatch):
|
|
| 32 |
assert model.rate_limiter is llm_factory._cloudflare_limiter
|
| 33 |
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
def test_daily_budget_rejects_additional_attempts():
|
| 36 |
limiter = llm_factory.CloudflareRateLimiter(daily_limit=2)
|
| 37 |
limiter._reserve()
|
|
@@ -59,6 +69,17 @@ def test_routing_keeps_host_and_tls_server_name():
|
|
| 59 |
_routed_request(httpx.Request('POST', 'https://elsewhere.example/'), '192.0.2.1')
|
| 60 |
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
def test_transport_tries_another_route_only_for_connect_failure():
|
| 63 |
class Routes:
|
| 64 |
def __init__(self):
|
|
|
|
| 32 |
assert model.rate_limiter is llm_factory._cloudflare_limiter
|
| 33 |
|
| 34 |
|
| 35 |
+
def test_gateway_supports_a_separate_gateway_token(monkeypatch):
|
| 36 |
+
monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'workers-ai-token')
|
| 37 |
+
monkeypatch.setenv('CLOUDFLARE_GATEWAY_TOKEN', 'gateway-run-token')
|
| 38 |
+
monkeypatch.setenv('CLOUDFLARE_ACCOUNT_ID', 'a' * 32)
|
| 39 |
+
monkeypatch.setenv('CLOUDFLARE_GATEWAY_ID', 'default')
|
| 40 |
+
model = llm_factory._get_cloudflare_chat()
|
| 41 |
+
assert model.default_headers['cf-aig-authorization'] == 'Bearer gateway-run-token'
|
| 42 |
+
assert model.openai_api_key.get_secret_value() == 'workers-ai-token'
|
| 43 |
+
|
| 44 |
+
|
| 45 |
def test_daily_budget_rejects_additional_attempts():
|
| 46 |
limiter = llm_factory.CloudflareRateLimiter(daily_limit=2)
|
| 47 |
limiter._reserve()
|
|
|
|
| 69 |
_routed_request(httpx.Request('POST', 'https://elsewhere.example/'), '192.0.2.1')
|
| 70 |
|
| 71 |
|
| 72 |
+
def test_gateway_routing_keeps_its_host_and_tls_server_name():
|
| 73 |
+
original = httpx.Request('POST', 'https://gateway.ai.cloudflare.com/v1/acct/default/compat/chat/completions',
|
| 74 |
+
headers={'Authorization': 'Bearer test-key'}, content=b'{}')
|
| 75 |
+
routed = _routed_request(original, '192.0.2.1', 'gateway.ai.cloudflare.com')
|
| 76 |
+
assert routed.url.host == '192.0.2.1'
|
| 77 |
+
assert routed.headers['Host'] == 'gateway.ai.cloudflare.com'
|
| 78 |
+
assert routed.extensions['sni_hostname'] == 'gateway.ai.cloudflare.com'
|
| 79 |
+
with pytest.raises(ValueError):
|
| 80 |
+
_routed_request(original, '192.0.2.1', 'not-cloudflare.example')
|
| 81 |
+
|
| 82 |
+
|
| 83 |
def test_transport_tries_another_route_only_for_connect_failure():
|
| 84 |
class Routes:
|
| 85 |
def __init__(self):
|