Sdm0 commited on
Commit
79832d5
·
verified ·
1 Parent(s): 8c88c8d

Deploy 230bc3a8

Browse files
.env.example CHANGED
@@ -16,6 +16,7 @@
16
  # Optional Cloudflare Workers AI default. Set both account ID and API token.
17
  # CLOUDFLARE_ACCOUNT_ID=your_account_id
18
  # CLOUDFLARE_API_TOKEN=your_workers_ai_token
 
19
  # CLOUDFLARE_MODEL=@cf/zai-org/glm-4.7-flash
20
  # CLOUDFLARE_DAILY_REQUEST_LIMIT=50
21
  # [REQUIRED - at least one] LLM API key for the AI reviewers.
 
16
  # Optional Cloudflare Workers AI default. Set both account ID and API token.
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.
README.md CHANGED
@@ -72,6 +72,8 @@ The model factory supports Cloudflare Workers AI, Groq and Google Gemini, plus c
72
 
73
  Set `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` to use Workers AI's `@cf/zai-org/glm-4.7-flash` by default for automatic reviews and evaluation. `CLOUDFLARE_MODEL` can override the model, and `CLOUDFLARE_DAILY_REQUEST_LIMIT` sets a conservative local rolling request budget (default 50). Calls are paced to one every five seconds and automatic provider retries are disabled. This per-process request budget resets on restart and does not measure Cloudflare's neuron usage or enforce account-wide limits. See [Workers AI pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/) and [limits](https://developers.cloudflare.com/workers-ai/platform/limits/).
74
 
 
 
75
  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.
76
 
77
  ## Try it locally
 
72
 
73
  Set `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_API_TOKEN` to use Workers AI's `@cf/zai-org/glm-4.7-flash` by default for automatic reviews and evaluation. `CLOUDFLARE_MODEL` can override the model, and `CLOUDFLARE_DAILY_REQUEST_LIMIT` sets a conservative local rolling request budget (default 50). Calls are paced to one every five seconds and automatic provider retries are disabled. This per-process request budget resets on restart and does not measure Cloudflare's neuron usage or enforce account-wide limits. See [Workers AI pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/) and [limits](https://developers.cloudflare.com/workers-ai/platform/limits/).
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
backend/api.py CHANGED
@@ -36,28 +36,7 @@ from backend.integrations.endpoints import register_endpoint, unregister_endpoin
36
  app = FastAPI(title="OpenCodeReview API", version="0.1.0")
37
  logger = logging.getLogger(__name__)
38
 
39
- def _temporary_host_probe():
40
- """Compare verified public TLS routes without sending credentials."""
41
- import socket
42
- import ssl
43
- from concurrent.futures import ThreadPoolExecutor
44
- def check(host, ip):
45
- try:
46
- with socket.create_connection((ip, 443), timeout=4) as conn:
47
- with ssl.create_default_context().wrap_socket(conn, server_hostname=host):
48
- return True
49
- except OSError:
50
- return False
51
- for host in ("api.cloudflare.com", "gateway.ai.cloudflare.com", "generativelanguage.googleapis.com"):
52
- try:
53
- ips = list(dict.fromkeys(x[4][0] for x in socket.getaddrinfo(host, 443, socket.AF_INET, socket.SOCK_STREAM)))[:8]
54
- with ThreadPoolExecutor(max_workers=max(1, len(ips))) as pool:
55
- ok = sum(pool.map(lambda ip: check(host, ip), ips))
56
- logger.warning("Host diagnostic: host=%s candidates=%d verified=%d", host, len(ips), ok)
57
- except Exception as exc:
58
- logger.warning("Host diagnostic: host=%s error=%s", host, type(exc).__name__)
59
-
60
- threading.Thread(target=_temporary_host_probe, daemon=True).start()
61
 
62
 
63
 
 
36
  app = FastAPI(title="OpenCodeReview API", version="0.1.0")
37
  logger = logging.getLogger(__name__)
38
 
39
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
 
42
 
backend/integrations/llm_factory.py CHANGED
@@ -4,6 +4,7 @@ from __future__ import annotations
4
 
5
  import logging
6
  import os
 
7
  import threading
8
  import time
9
  from collections import deque
@@ -119,8 +120,13 @@ def _get_cloudflare_chat(**kwargs: Any) -> Optional[Any]:
119
  """Use Workers AI when an account ID and API token are configured."""
120
  api_key = os.environ.get("CLOUDFLARE_API_TOKEN", "").strip()
121
  account_id = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "").strip()
 
122
  if not api_key or not account_id:
123
  return None
 
 
 
 
124
  from langchain_openai import ChatOpenAI
125
  import httpx
126
  timeout = kwargs.pop("timeout", DEFAULT_REQUEST_TIMEOUT)
@@ -129,15 +135,29 @@ def _get_cloudflare_chat(**kwargs: Any) -> Optional[Any]:
129
  # Retry only failures while establishing a connection, before an HTTP
130
  # request is sent. Preserve normal TLS certificate and hostname checks.
131
  # IPv6 is unavailable on the hosted Space; keep DNS and TLS SNI intact.
132
- kwargs.setdefault("http_client", httpx.Client(transport=CloudflareTransport(_cloudflare_routes), timeout=timeout))
133
- kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=AsyncCloudflareTransport(_cloudflare_routes), timeout=timeout))
 
 
 
 
 
 
 
 
 
 
 
134
  kwargs["timeout"] = timeout
135
  kwargs.setdefault("max_retries", 0)
136
  kwargs["max_tokens"] = max(int(kwargs.get("max_tokens") or DEFAULT_OUTPUT_TOKENS), 4096)
137
  kwargs.setdefault("reasoning_effort", "low")
138
  kwargs.setdefault("rate_limiter", _cloudflare_limiter)
139
- return ChatOpenAI(model=kwargs.pop("model", CLOUDFLARE_MODEL), api_key=api_key,
140
- base_url=f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1",
 
 
 
141
  temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE), **kwargs)
142
 
143
 
 
4
 
5
  import logging
6
  import os
7
+ import re
8
  import threading
9
  import time
10
  from collections import deque
 
120
  """Use Workers AI when an account ID and API token are configured."""
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):
127
+ raise ValueError("CLOUDFLARE_ACCOUNT_ID must be a 32-character hexadecimal account ID.")
128
+ if gateway_id and not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", gateway_id):
129
+ raise ValueError("CLOUDFLARE_GATEWAY_ID contains invalid characters.")
130
  from langchain_openai import ChatOpenAI
131
  import httpx
132
  timeout = kwargs.pop("timeout", DEFAULT_REQUEST_TIMEOUT)
 
135
  # Retry only failures while establishing a connection, before an HTTP
136
  # request is sent. Preserve normal TLS certificate and hostname checks.
137
  # IPv6 is unavailable on the hosted Space; keep DNS and TLS SNI intact.
138
+ if gateway_id:
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=httpx.HTTPTransport(local_address="0.0.0.0", retries=2), timeout=timeout))
145
+ kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=httpx.AsyncHTTPTransport(local_address="0.0.0.0", retries=2), timeout=timeout))
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))
149
+ kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=AsyncCloudflareTransport(_cloudflare_routes), timeout=timeout))
150
+ base_url = f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1"
151
  kwargs["timeout"] = timeout
152
  kwargs.setdefault("max_retries", 0)
153
  kwargs["max_tokens"] = max(int(kwargs.get("max_tokens") or DEFAULT_OUTPUT_TOKENS), 4096)
154
  kwargs.setdefault("reasoning_effort", "low")
155
  kwargs.setdefault("rate_limiter", _cloudflare_limiter)
156
+ model = kwargs.pop("model", CLOUDFLARE_MODEL)
157
+ if gateway_id and model.startswith("@cf/"):
158
+ model = f"workers-ai/{model}"
159
+ return ChatOpenAI(model=model, api_key=api_key,
160
+ base_url=base_url,
161
  temperature=kwargs.pop("temperature", DEFAULT_TEMPERATURE), **kwargs)
162
 
163
 
nodes/review_runtime.py CHANGED
@@ -53,7 +53,7 @@ def invoke_review(llm, schema, messages, mode="thorough"):
53
  underlying connections; timed-out workers never modify graph state.
54
  """
55
  budget = reviewer_timeout(mode)
56
- if str(getattr(llm, "model_name", "")).startswith("@cf/"):
57
  budget = max(budget, float(os.getenv("OCR_CLOUDFLARE_REVIEWER_TIMEOUT_SECONDS", "180")))
58
  deadline = time.monotonic() + budget
59
  instructions = (
 
53
  underlying connections; timed-out workers never modify graph state.
54
  """
55
  budget = reviewer_timeout(mode)
56
+ if str(getattr(llm, "model_name", "")).removeprefix("workers-ai/").startswith("@cf/"):
57
  budget = max(budget, float(os.getenv("OCR_CLOUDFLARE_REVIEWER_TIMEOUT_SECONDS", "180")))
58
  deadline = time.monotonic() + budget
59
  instructions = (
tests/test_cloudflare_provider.py CHANGED
@@ -8,10 +8,11 @@ from backend.integrations.cloudflare_transport import CloudflareTransport, _rout
8
 
9
  def test_cloudflare_default_and_shared_pacing(monkeypatch):
10
  monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-key')
11
- monkeypatch.setenv('CLOUDFLARE_ACCOUNT_ID', 'test-account')
 
12
  model = llm_factory._get_cloudflare_chat()
13
  assert model.model_name == '@cf/zai-org/glm-4.7-flash'
14
- assert str(model.openai_api_base) == 'https://api.cloudflare.com/client/v4/accounts/test-account/ai/v1'
15
  assert model.max_retries == 0
16
  assert model.max_tokens >= 4096
17
  assert model.reasoning_effort == 'low'
@@ -19,6 +20,18 @@ def test_cloudflare_default_and_shared_pacing(monkeypatch):
19
  assert llm_factory.create_llm().rate_limiter is model.rate_limiter
20
 
21
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def test_daily_budget_rejects_additional_attempts():
23
  limiter = llm_factory.CloudflareRateLimiter(daily_limit=2)
24
  limiter._reserve()
 
8
 
9
  def test_cloudflare_default_and_shared_pacing(monkeypatch):
10
  monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-key')
11
+ monkeypatch.setenv('CLOUDFLARE_ACCOUNT_ID', 'a' * 32)
12
+ monkeypatch.delenv('CLOUDFLARE_GATEWAY_ID', raising=False)
13
  model = llm_factory._get_cloudflare_chat()
14
  assert model.model_name == '@cf/zai-org/glm-4.7-flash'
15
+ assert str(model.openai_api_base) == f'https://api.cloudflare.com/client/v4/accounts/{"a" * 32}/ai/v1'
16
  assert model.max_retries == 0
17
  assert model.max_tokens >= 4096
18
  assert model.reasoning_effort == 'low'
 
20
  assert llm_factory.create_llm().rate_limiter is model.rate_limiter
21
 
22
 
23
+ def test_gateway_uses_cloudflare_model_and_disables_cache_and_logs(monkeypatch):
24
+ monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-key')
25
+ monkeypatch.setenv('CLOUDFLARE_ACCOUNT_ID', 'a' * 32)
26
+ monkeypatch.setenv('CLOUDFLARE_GATEWAY_ID', 'default')
27
+ model = llm_factory._get_cloudflare_chat()
28
+ assert model.model_name == 'workers-ai/@cf/zai-org/glm-4.7-flash'
29
+ assert str(model.openai_api_base) == f'https://gateway.ai.cloudflare.com/v1/{"a" * 32}/default/compat'
30
+ assert model.default_headers['cf-aig-collect-log'] == 'false'
31
+ assert model.default_headers['cf-aig-skip-cache'] == 'true'
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()