Sdm0 commited on
Commit
c3fca85
Β·
verified Β·
1 Parent(s): 081523d

Deploy 0a52a600

Browse files
Files changed (3) hide show
  1. app.py +294 -120
  2. eval_data/ragas_eval.py +103 -5
  3. opencodereview-spec.md +335 -0
app.py CHANGED
@@ -551,17 +551,18 @@ def _format_findings_count(findings: list) -> str:
551
 
552
 
553
  def _format_run_summary(
554
- repo: str, pr_number: int, endpoint_name: str, duration: float, cost_summary: str
555
  ) -> str:
556
  """Build a compact run-summary card shown above the results."""
557
  endpoint_display = html.escape(endpoint_name or "built-in default")
 
558
  return (
559
  '<div class="ocr-card" style="margin-top:12px">'
560
  '<div class="run-summary">'
561
  f'<span>πŸ“¦ <b>{html.escape(repo)}</b>#{pr_number}</span>'
562
  f'<span>πŸ€– <b>{endpoint_display}</b></span>'
563
  f'<span>⏱️ <b>{duration:.1f}s</b></span>'
564
- f'<span>{cost_summary}</span>'
565
  "</div>"
566
  "</div>"
567
  )
@@ -573,7 +574,7 @@ def _format_session_endpoints() -> str:
573
  if not eps:
574
  return (
575
  '<p class="muted small">No endpoints added in this session yet β€” '
576
- "fill the form above and click <b>Save & use endpoint</b>.</p>"
577
  )
578
  cards = "".join(
579
  f'<div class="endpoint-card">'
@@ -591,7 +592,16 @@ def _format_session_endpoints() -> str:
591
 
592
 
593
  def _probe_endpoint(ep) -> tuple[bool, str]:
594
- """Quick connectivity probe for a custom endpoint (no LLM generation)."""
 
 
 
 
 
 
 
 
 
595
  import urllib.request as _ur
596
 
597
  if ep.provider == "google":
@@ -603,21 +613,21 @@ def _probe_endpoint(ep) -> tuple[bool, str]:
603
  except Exception as exc:
604
  return False, f"{type(exc).__name__}: {exc}"[:140]
605
 
 
 
 
 
 
 
 
606
  if ep.provider == "anthropic":
607
  base = (ep.base_url or "https://api.anthropic.com/v1").rstrip("/")
608
  candidates = [f"{base}/models"]
609
  if not base.endswith("/v1"):
610
  candidates.append(f"{base}/v1/models")
611
- else: # openai-compatible
612
- base = (ep.base_url or "https://api.openai.com/v1").rstrip("/")
613
- candidates = [f"{base}/models"]
614
- if not base.endswith("/v1"):
615
- candidates.append(f"{base}/v1/models")
616
-
617
- last_err = "no response"
618
- for url in candidates:
619
- try:
620
- if ep.provider == "anthropic":
621
  req = _ur.Request(
622
  url,
623
  headers={
@@ -625,16 +635,69 @@ def _probe_endpoint(ep) -> tuple[bool, str]:
625
  "anthropic-version": "2023-06-01",
626
  },
627
  )
628
- else:
629
- req = _ur.Request(
630
- url, headers={"Authorization": f"Bearer {ep.api_key}"}
631
- )
632
- with _ur.urlopen(req, timeout=10) as resp:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633
  if resp.status == 200:
634
  return True, f"HTTP 200 Β· {url}"
 
 
 
 
635
  except Exception as exc:
636
- last_err = f"{type(exc).__name__}: {exc}"
637
- return False, last_err[:140]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
638
 
639
 
640
  def test_endpoints() -> str:
@@ -669,7 +732,7 @@ def test_endpoints() -> str:
669
  f'<div class="endpoint-meta"><code>{ep.model}</code>'
670
  f' Β· {ep.base_url or "default URL"} Β· key {ep.masked_key}</div>'
671
  f'<div class="endpoint-meta" style="color:{status_color};font-weight:700">'
672
- f'{"βœ… reachable" if ok else "❌ unreachable"} β€” {detail}</div>'
673
  f'</div>'
674
  )
675
  return '<div>' + "".join(cards) + '</div>'
@@ -735,7 +798,7 @@ def run_review(repo: str, pr_number: int, endpoint_name: str = "", progress=gr.P
735
  t0 = time.time()
736
  try:
737
  state, config, cost_summary, ragas_out = _build_and_stream(
738
- repo.strip(), pr_number, endpoint_name, ragas_background=True,
739
  )
740
  except Exception as exc:
741
  log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
@@ -890,9 +953,6 @@ def run_smoke(progress=gr.Progress()):
890
  yield [verdict_html, findings_html + cost_html, config_json, verdict_html, findings_html], None
891
 
892
 
893
-
894
-
895
-
896
  # ─── UI ──────────────────────────────────────────────────────────────────────
897
 
898
  CSS = """
@@ -908,57 +968,135 @@ CSS = """
908
  --text-muted: #64748b;
909
  --text-footer: #94a3b8;
910
  --spinner-track: #e2e8f0;
911
- --accent: #6366f1;
912
- --accent-soft: rgba(99, 102, 241, 0.12);
 
 
 
 
 
 
913
  --radius: 14px;
914
  --shadow: 0 1px 2px rgba(15, 23, 42, 0.05), 0 10px 30px rgba(15, 23, 42, 0.06);
915
  }
916
 
917
- /* ── Dark Mode Overrides ─────────────────────────────────────────── */
918
- body.dark-mode {
919
- --bg-page: #0b1220;
920
- --bg-card: #131c31;
921
- --bg-card-alt: #0f172a;
922
- --bg-table-header: #1e293b;
923
- --border-color: #2b3a55;
924
- --text-primary: #f1f5f9;
925
- --text-secondary: #cbd5e1;
926
- --text-muted: #94a3b8;
927
- --text-footer: #64748b;
928
- --spinner-track: #334155;
929
- --accent: #818cf8;
930
- --accent-soft: rgba(129, 140, 248, 0.15);
931
- --shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 10px 30px rgba(0, 0, 0, 0.3);
 
 
 
 
 
 
932
  }
933
- body.dark-mode .gradio-container {
934
- background: radial-gradient(1200px 500px at 20% -10%, #1e1b4b33, transparent 60%),
935
- radial-gradient(1000px 400px at 90% 10%, #17255433, transparent 55%),
936
- var(--bg-page) !important;
 
 
 
 
 
 
 
 
 
 
 
 
937
  }
938
- body.dark-mode .gr-box,
939
- body.dark-mode .tabs,
940
- body.dark-mode .tab-nav {
941
- background-color: var(--bg-card) !important;
942
- border-color: var(--border-color) !important;
 
 
 
 
943
  }
944
- body.dark-mode input, body.dark-mode textarea, body.dark-mode select {
945
- background-color: var(--bg-card-alt) !important;
946
  color: var(--text-primary) !important;
947
- border-color: var(--border-color) !important;
948
  }
949
- body.dark-mode label { color: var(--text-secondary) !important; }
950
- body.dark-mode button:not(.lg) { color: var(--text-primary) !important; }
951
- body.dark-mode .footer { color: var(--text-footer) !important; }
952
- body.dark-mode details summary { color: var(--text-secondary) !important; }
953
- body.dark-mode [data-testid="block-info"] { color: var(--text-muted) !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
954
 
955
  /* ── Global ──────────────────────────────────────────────────────── */
 
 
 
 
 
 
 
956
  .gradio-container {
957
  background: radial-gradient(1200px 500px at 20% -10%, #eef2ff66, transparent 60%),
958
  radial-gradient(1000px 400px at 90% 10%, #e0f2fe55, transparent 55%),
959
  var(--bg-page) !important;
960
  }
961
- .gr-container { max-width: 980px; margin: 0 auto; }
962
  .footer { text-align: center; color: var(--text-footer); font-size: 0.85em; padding: 22px 0; }
963
  details { margin-top: 8px; }
964
  details summary { cursor: pointer; color: var(--text-secondary); font-weight: 500; }
@@ -969,45 +1107,52 @@ code { background: var(--bg-card-alt); padding: 1px 6px; border-radius: 6px; fon
969
  /* ── Hero ────────────────────────────────────────────────────────── */
970
  .hero { display: flex; align-items: center; gap: 16px; padding: 8px 0 4px; }
971
  .hero-icon {
972
- font-size: 2.2em; width: 58px; height: 58px; display: flex; align-items: center;
973
- justify-content: center; border-radius: 16px;
974
- background: linear-gradient(135deg, #6366f1, #8b5cf6);
975
- box-shadow: 0 8px 20px rgba(99, 102, 241, 0.35);
 
 
976
  }
977
- .hero-title { margin: 0; font-size: 1.6em; font-weight: 800; letter-spacing: -0.02em; color: var(--text-primary); }
978
  .hero-sub { margin: 2px 0 0; color: var(--text-muted); font-size: 0.95em; }
979
 
980
  /* ── Cards ───────────────────────────────────────────────────────── */
981
  .ocr-card {
982
- background: var(--bg-card); border: 1px solid var(--border-color);
 
983
  border-radius: var(--radius); padding: 16px 20px; margin-top: 12px;
984
- box-shadow: var(--shadow);
 
985
  }
986
- .card-title { font-weight: 700; color: var(--text-primary); margin-bottom: 12px; font-size: 1.02em; }
987
  .chips-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
988
 
989
  /* ── Chips / badges ──────────────────────────────────────────────── */
990
  .key-chip {
991
  display: inline-block; padding: 3px 12px; border-radius: 999px;
992
- font-size: 0.85em; font-weight: 600; border: 1px solid;
 
 
993
  }
994
- .key-chip.ok { color: #16a34a; background: #16a34a14; border-color: #16a34a44; }
995
- .key-chip.no { color: var(--text-muted); background: var(--bg-card-alt); border-color: var(--border-color); }
996
  .sev-chip {
997
  display: inline-block; padding: 3px 12px; border-radius: 999px;
998
- font-size: 0.85em; font-weight: 700; border: 1px solid;
 
999
  }
1000
 
1001
  /* ── Endpoint cards ──────────────────────────────────────────────── */
1002
  .endpoint-card {
1003
- border: 1px solid var(--border-color); border-radius: 10px;
1004
- padding: 10px 14px; margin-bottom: 8px; background: var(--bg-card-alt);
 
1005
  }
1006
- .endpoint-name { font-weight: 700; color: var(--text-primary); display: flex; gap: 8px; align-items: center; }
1007
  .endpoint-badge {
1008
- font-size: 0.72em; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em;
1009
- padding: 2px 8px; border-radius: 999px; color: var(--accent);
1010
- background: var(--accent-soft); border: 1px solid #6366f144;
1011
  }
1012
  .endpoint-meta { margin-top: 4px; font-size: 0.88em; color: var(--text-secondary); }
1013
 
@@ -1043,12 +1188,14 @@ tbody tr:hover { background: var(--bg-card-alt); }
1043
 
1044
  /* ── Theme toggle ���───────────────────────────────────────────────── */
1045
  #theme-toggle-btn {
1046
- float: right; margin-top: 18px !important; background: transparent !important;
1047
- border: 1px solid var(--border-color) !important; border-radius: 10px !important;
1048
  padding: 4px 10px !important; font-size: 1.1em !important; min-width: 44px !important;
1049
- transition: all 0.2s ease !important; box-shadow: none !important;
 
 
1050
  }
1051
- #theme-toggle-btn:hover { background: var(--bg-card-alt) !important; border-color: var(--text-muted) !important; }
1052
 
1053
  /* ── Loading spinner ─────────────────────────────────────────────── */
1054
  @keyframes spin { to { transform: rotate(360deg); } }
@@ -1064,16 +1211,21 @@ tbody tr:hover { background: var(--bg-card-alt); }
1064
 
1065
  JS_RESTORE_THEME = """
1066
  () => {
1067
- const isDark = localStorage.getItem("ocr-theme") === "dark";
1068
- if (isDark) document.body.classList.add("dark-mode");
 
 
 
 
 
1069
  const btn = document.querySelector("#theme-toggle-btn");
1070
- if (btn) btn.textContent = isDark ? "β˜€οΈ" : "πŸŒ™";
1071
  }
1072
  """
1073
 
1074
  JS_TOGGLE_THEME = """
1075
  () => {
1076
- const isDark = document.body.classList.toggle("dark-mode");
1077
  localStorage.setItem("ocr-theme", isDark ? "dark" : "light");
1078
  const btn = document.querySelector("#theme-toggle-btn");
1079
  if (btn) btn.textContent = isDark ? "β˜€οΈ" : "πŸŒ™";
@@ -1102,15 +1254,15 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1102
  with gr.Column(scale=4):
1103
  gr.HTML(
1104
  '<div class="hero">'
1105
- '<div class="hero-icon">πŸ”</div>'
1106
  '<div>'
1107
  '<h1 class="hero-title">OpenCodeReview</h1>'
1108
  '<p class="hero-sub">AI-powered PR review with human-in-the-loop approval</p>'
1109
  f'<div class="chips-row" style="margin-top:8px">'
1110
- f'<span class="key-chip ok">⚑ {len(_configured_endpoints)} endpoint'
1111
- f'{"s" if len(_configured_endpoints) != 1 else ""}</span>'
1112
- '<span class="key-chip" style="color:var(--accent);background:var(--accent-soft);border-color:#6366f144">✨ Gemini · Grok built-ins</span>'
1113
- '<span class="key-chip" style="color:var(--text-muted);background:var(--bg-card-alt);border-color:var(--border-color)">πŸ” BYO keys</span>'
1114
  '</div>'
1115
  '</div>'
1116
  '</div>'
@@ -1126,8 +1278,8 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1126
  # it so review results render immediately instead of waiting on RAGAS.
1127
  ragas_task_state = gr.State(value="")
1128
 
1129
- # ── Tab: Review a PR ─────────────────────────────────────────────────
1130
- with gr.Tab("Review a PR"):
1131
  with gr.Row():
1132
  repo_input = gr.Textbox(
1133
  label="Repository",
@@ -1148,8 +1300,8 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1148
  value="",
1149
  label="LLM Endpoint",
1150
  info=(
1151
- "Built-in: Gemini & Grok. Pick one, or add your own below. "
1152
- "Empty = auto (Gemini β†’ Grok fallback)."
1153
  ),
1154
  # Grouped optgroup choices make Gradio's strict membership
1155
  # check reject values that sit inside a group (e.g. a custom
@@ -1159,14 +1311,14 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1159
  allow_custom_value=True,
1160
  scale=3,
1161
  )
1162
- test_selected_btn = gr.Button("πŸ”Œ Test selected", size="sm", scale=1)
1163
  endpoint_test_msg = gr.Markdown()
1164
 
1165
  def on_test_selected(endpoint_name):
1166
  """Probe the currently selected endpoint (built-in or custom)."""
1167
  if not endpoint_name:
1168
  return (
1169
- "ℹ️ Leave the endpoint empty for auto (Gemini β†’ Grok fallback), "
1170
  "or pick one and test it here."
1171
  )
1172
  from endpoints import get_endpoint
@@ -1191,7 +1343,7 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1191
  )
1192
 
1193
  # ── Add your own endpoint (BYO key) ─────────────────────────
1194
- with gr.Accordion("βž• Add custom endpoint (BYO key)", open=False):
1195
  with gr.Row():
1196
  ep_name_input = gr.Textbox(
1197
  label="Endpoint name",
@@ -1222,15 +1374,15 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1222
  placeholder="sk-... (stored in memory only, never written to disk)",
1223
  )
1224
  with gr.Row():
1225
- test_form_btn = gr.Button("πŸ”Œ Test this endpoint", size="sm")
1226
- add_endpoint_btn = gr.Button("πŸ’Ύ Save & use endpoint", variant="primary", size="sm")
1227
- clear_endpoints_btn = gr.Button("πŸ—‘ Clear added endpoints", size="sm")
1228
  endpoint_save_msg = gr.Markdown()
1229
  session_endpoints_display = gr.HTML(value=_format_session_endpoints())
1230
 
1231
  with gr.Row():
1232
- run_btn = gr.Button("β–Ά Run Review", variant="primary", size="lg", scale=2)
1233
- cancel_btn = gr.Button("⏹ Cancel", variant="stop", size="lg", visible=False)
1234
 
1235
  loading_box = gr.HTML(
1236
  '<div class="loading-spinner"><div class="spinner"></div>'
@@ -1247,15 +1399,18 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1247
  ragas_display = gr.HTML()
1248
 
1249
  with gr.Row():
1250
- approve_btn = gr.Button("βœ… Approve & Post", variant="primary")
1251
- reject_btn = gr.Button("❌ Reject", variant="secondary")
1252
 
1253
  resume_msg = gr.Markdown()
1254
 
1255
  # ── Event wiring ──────────────────────────────────────────────
1256
  def on_run_click(*args):
1257
  """Generator that clears old state, runs review, shows results."""
1258
- # Yield initial loading state
 
 
 
1259
  yield [
1260
  gr.update(visible=True),
1261
  gr.update(visible=True, variant="stop"),
@@ -1461,8 +1616,8 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1461
  ok, detail = _probe_endpoint(cfg)
1462
  icon = "βœ…" if ok else "❌"
1463
  if ok:
1464
- return f"{icon} **{name}** (`{model}`) reachable β€” {detail}"
1465
- return f"{icon} **{name}** unreachable β€” {detail}"
1466
 
1467
  test_form_btn.click(
1468
  fn=on_test_form,
@@ -1476,15 +1631,14 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1476
  outputs=[endpoint_save_msg],
1477
  )
1478
 
1479
- # ── Tab: Smoke Test ──────────────────────────────────────────────────
1480
- with gr.Tab("Smoke Test"):
1481
  gr.Markdown(
1482
- "Run the review pipeline on **synthetic demo data** "
1483
- "(no API keys needed, no interrupt required)."
1484
  )
1485
  with gr.Row():
1486
- smoke_btn = gr.Button("β–Ά Run Smoke Test", variant="primary", size="lg", scale=2)
1487
- smoke_cancel_btn = gr.Button("⏹ Cancel", variant="stop", size="lg", visible=False)
1488
 
1489
  smoke_loading = gr.HTML(
1490
  '<div class="loading-spinner"><div class="spinner"></div>'
@@ -1496,8 +1650,8 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1496
  smoke_verdict = gr.HTML()
1497
  smoke_findings = gr.HTML()
1498
  with gr.Row():
1499
- smoke_approve = gr.Button("βœ… Approve (demo)", variant="primary")
1500
- smoke_reject = gr.Button("❌ Reject (demo)", variant="secondary")
1501
  smoke_resume_msg = gr.Markdown()
1502
 
1503
  smoke_status = gr.Markdown(visible=False)
@@ -1558,7 +1712,7 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1558
  )
1559
 
1560
  # ── Environment status footer ──────────────────────────────────────
1561
- with gr.Accordion("πŸ”‘ Configured Keys & Health", open=False):
1562
  h = HealthStatus()
1563
  health_data = h.summary()
1564
  gemini_ok = bool(os.environ.get("GEMINI_API_KEY", "").strip())
@@ -1600,7 +1754,7 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1600
  'as Space secrets to add one.</p>'
1601
  )
1602
  with gr.Row():
1603
- test_endpoints_btn = gr.Button("πŸ”Œ Test endpoint connectivity", size="sm", variant="secondary")
1604
  endpoint_test_out = gr.HTML()
1605
  test_endpoints_btn.click(fn=test_endpoints, outputs=[endpoint_test_out])
1606
 
@@ -1615,8 +1769,28 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1615
  )
1616
 
1617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1618
  def main() -> None:
1619
- port = int(os.environ.get("PORT", 7860))
1620
  # Gradio 6: theme/css moved from the Blocks constructor to launch().
1621
  demo.queue(max_size=10).launch(
1622
  server_name="0.0.0.0",
 
551
 
552
 
553
  def _format_run_summary(
554
+ repo: str, pr_number: int, endpoint_name: str, duration: float, cost_summary: str | dict
555
  ) -> str:
556
  """Build a compact run-summary card shown above the results."""
557
  endpoint_display = html.escape(endpoint_name or "built-in default")
558
+ cost_text = cost_summary if isinstance(cost_summary, str) else str(cost_summary)
559
  return (
560
  '<div class="ocr-card" style="margin-top:12px">'
561
  '<div class="run-summary">'
562
  f'<span>πŸ“¦ <b>{html.escape(repo)}</b>#{pr_number}</span>'
563
  f'<span>πŸ€– <b>{endpoint_display}</b></span>'
564
  f'<span>⏱️ <b>{duration:.1f}s</b></span>'
565
+ f'<span>πŸ’° {html.escape(cost_text)}</span>'
566
  "</div>"
567
  "</div>"
568
  )
 
574
  if not eps:
575
  return (
576
  '<p class="muted small">No endpoints added in this session yet β€” '
577
+ "fill the form above and click <b>Save &amp; use endpoint</b>.</p>"
578
  )
579
  cards = "".join(
580
  f'<div class="endpoint-card">'
 
592
 
593
 
594
  def _probe_endpoint(ep) -> tuple[bool, str]:
595
+ """Probe an endpoint and report whether it can serve the pipeline.
596
+
597
+ HTTP status codes are classified so a 401/403 is reported as
598
+ "reachable but the server rejected the key" instead of a misleading
599
+ "unreachable". OpenAI-compatible servers that don't implement
600
+ ``GET /models`` (many vLLM / proxy deployments) fall back to a
601
+ minimal ``/chat/completions`` call β€” the real request the pipeline
602
+ makes β€” so a blocked /models endpoint no longer looks broken.
603
+ """
604
+ import urllib.error as _ur_err
605
  import urllib.request as _ur
606
 
607
  if ep.provider == "google":
 
613
  except Exception as exc:
614
  return False, f"{type(exc).__name__}: {exc}"[:140]
615
 
616
+ def _auth_rejected(exc: _ur_err.HTTPError) -> str:
617
+ return (
618
+ f"endpoint is reachable but the server rejected the API key "
619
+ f"(HTTP {exc.code}) β€” check the key and auth type"
620
+ )
621
+
622
+ # ── Anthropic ────────────────────────────────────────────────
623
  if ep.provider == "anthropic":
624
  base = (ep.base_url or "https://api.anthropic.com/v1").rstrip("/")
625
  candidates = [f"{base}/models"]
626
  if not base.endswith("/v1"):
627
  candidates.append(f"{base}/v1/models")
628
+ last_err = "no models endpoint responded"
629
+ for url in candidates:
630
+ try:
 
 
 
 
 
 
 
631
  req = _ur.Request(
632
  url,
633
  headers={
 
635
  "anthropic-version": "2023-06-01",
636
  },
637
  )
638
+ with _ur.urlopen(req, timeout=30) as resp:
639
+ if resp.status == 200:
640
+ return True, f"HTTP 200 Β· {url}"
641
+ except _ur_err.HTTPError as exc:
642
+ if exc.code in (401, 403):
643
+ # Same key on every candidate β€” auth failure is final.
644
+ return False, f"{_auth_rejected(exc)} ({url})"
645
+ hint = " β€” check base_url (should end in /v1)" if exc.code == 404 else ""
646
+ last_err = f"reachable but returned HTTP {exc.code} ({url}){hint}"
647
+ except Exception as exc:
648
+ return False, f"unreachable β€” {type(exc).__name__}: {exc}"[:140]
649
+ return False, last_err
650
+
651
+ # ── OpenAI-compatible ────────────────────────────────────────
652
+ base = (ep.base_url or "https://api.openai.com/v1").rstrip("/")
653
+ candidates = [f"{base}/models"]
654
+ if not base.endswith("/v1"):
655
+ candidates.append(f"{base}/v1/models")
656
+
657
+ for url in candidates:
658
+ try:
659
+ req = _ur.Request(
660
+ url, headers={"Authorization": f"Bearer {ep.api_key}"}
661
+ )
662
+ with _ur.urlopen(req, timeout=30) as resp:
663
  if resp.status == 200:
664
  return True, f"HTTP 200 Β· {url}"
665
+ except _ur_err.HTTPError as exc:
666
+ if exc.code in (401, 403):
667
+ # Bad key on /models means chat would fail the same way.
668
+ return False, f"{_auth_rejected(exc)} ({url})"
669
  except Exception as exc:
670
+ # Genuinely unreachable β€” chat probe below would only repeat it.
671
+ return False, f"unreachable β€” {type(exc).__name__}: {exc}"[:140]
672
+
673
+ # /models missing or blocked (404/405/501…) β€” probe the real call.
674
+ try:
675
+ payload = json.dumps({
676
+ "model": ep.model,
677
+ "messages": [{"role": "user", "content": "ping"}],
678
+ "max_tokens": 1,
679
+ }).encode()
680
+ chat_url = f"{base}/chat/completions"
681
+ req = _ur.Request(
682
+ chat_url,
683
+ data=payload,
684
+ headers={
685
+ "Authorization": f"Bearer {ep.api_key}",
686
+ "Content-Type": "application/json",
687
+ },
688
+ method="POST",
689
+ )
690
+ with _ur.urlopen(req, timeout=30) as resp:
691
+ if resp.status == 200:
692
+ return True, f"chat/completions OK Β· {chat_url}"
693
+ return False, f"reachable but returned HTTP {resp.status} (chat/completions)"
694
+ except _ur_err.HTTPError as exc:
695
+ if exc.code in (401, 403):
696
+ return False, f"{_auth_rejected(exc)} (chat/completions)"
697
+ hint = " β€” check base_url (should end in /v1)" if exc.code == 404 else ""
698
+ return False, f"reachable but returned HTTP {exc.code} (chat/completions){hint}"
699
+ except Exception as exc:
700
+ return False, f"unreachable β€” {type(exc).__name__}: {exc}"[:140]
701
 
702
 
703
  def test_endpoints() -> str:
 
732
  f'<div class="endpoint-meta"><code>{ep.model}</code>'
733
  f' Β· {ep.base_url or "default URL"} Β· key {ep.masked_key}</div>'
734
  f'<div class="endpoint-meta" style="color:{status_color};font-weight:700">'
735
+ f'{"βœ…" if ok else "❌"} {detail}</div>'
736
  f'</div>'
737
  )
738
  return '<div>' + "".join(cards) + '</div>'
 
798
  t0 = time.time()
799
  try:
800
  state, config, cost_summary, ragas_out = _build_and_stream(
801
+ repo.strip(), int(pr_number), endpoint_name, ragas_background=True,
802
  )
803
  except Exception as exc:
804
  log_error_to_backends(exc, context={"source": "gradio_ui", "phase": "run_review", "repo": repo, "pr_number": pr_number})
 
953
  yield [verdict_html, findings_html + cost_html, config_json, verdict_html, findings_html], None
954
 
955
 
 
 
 
956
  # ─── UI ──────────────────────────────────────────────────────────────────────
957
 
958
  CSS = """
 
968
  --text-muted: #64748b;
969
  --text-footer: #94a3b8;
970
  --spinner-track: #e2e8f0;
971
+ --accent: #52525b;
972
+ --accent-soft: rgba(82, 82, 91, 0.10);
973
+ --glass: rgba(255, 255, 255, 0.55);
974
+ --glass-border: rgba(15, 23, 42, 0.10);
975
+ --glass-field: rgba(255, 255, 255, 0.72);
976
+ --glass-edge: rgba(15, 23, 42, 0.18);
977
+ --glass-hover: rgba(15, 23, 42, 0.05);
978
+ --glass-highlight: inset 0 1px 0 rgba(255, 255, 255, 0.8);
979
  --radius: 14px;
980
  --shadow: 0 1px 2px rgba(15, 23, 42, 0.05), 0 10px 30px rgba(15, 23, 42, 0.06);
981
  }
982
 
983
+ /* ── Dark Mode β€” true black, glass surfaces, no blue ────────────── */
984
+ body.dark {
985
+ --bg-page: #000000;
986
+ --bg-card: #0a0a0a;
987
+ --bg-card-alt: #101010;
988
+ --bg-table-header: #0a0a0a;
989
+ --border-color: #1f1f1f;
990
+ --text-primary: #f5f5f5;
991
+ --text-secondary: #d4d4d4;
992
+ --text-muted: #8a8a8a;
993
+ --text-footer: #5c5c5c;
994
+ --spinner-track: #1c1c1c;
995
+ --accent: #a1a1aa;
996
+ --accent-soft: rgba(255, 255, 255, 0.07);
997
+ --shadow: none;
998
+ --glass: rgba(255, 255, 255, 0.035);
999
+ --glass-border: rgba(255, 255, 255, 0.09);
1000
+ --glass-field: rgba(255, 255, 255, 0.045);
1001
+ --glass-edge: rgba(255, 255, 255, 0.12);
1002
+ --glass-hover: rgba(255, 255, 255, 0.12);
1003
+ --glass-highlight: inset 0 1px 0 rgba(255, 255, 255, 0.07);
1004
  }
1005
+ /* Glass buttons β€” replace Gradio's solid blue primary / gray secondary
1006
+ with frosted neutral surfaces (scoped to the app area, not Gradio's
1007
+ own footer controls). */
1008
+ .gradio-container main button.primary {
1009
+ background: var(--glass-hover) !important;
1010
+ color: var(--text-primary) !important;
1011
+ border: 1px solid var(--glass-edge) !important;
1012
+ border-radius: 12px !important;
1013
+ font-weight: 600 !important;
1014
+ box-shadow: var(--glass-highlight) !important;
1015
+ backdrop-filter: blur(12px) !important;
1016
+ transition: background 0.18s ease, border-color 0.18s ease !important;
1017
+ }
1018
+ .gradio-container main button.primary:hover {
1019
+ background: var(--accent-soft) !important;
1020
+ border-color: var(--text-muted) !important;
1021
  }
1022
+ .gradio-container main button:not(.primary) {
1023
+ background: var(--glass) !important;
1024
+ color: var(--text-secondary) !important;
1025
+ border: 1px solid var(--glass-border) !important;
1026
+ border-radius: 12px !important;
1027
+ font-weight: 500 !important;
1028
+ box-shadow: var(--glass-highlight) !important;
1029
+ backdrop-filter: blur(10px) !important;
1030
+ transition: background 0.18s ease, color 0.18s ease, border-color 0.18s ease !important;
1031
  }
1032
+ .gradio-container main button:not(.primary):hover {
1033
+ background: var(--glass-hover) !important;
1034
  color: var(--text-primary) !important;
1035
+ border-color: var(--glass-edge) !important;
1036
  }
1037
+ /* Frosted input fields in both themes. */
1038
+ .gradio-container input, .gradio-container textarea, .gradio-container select {
1039
+ background-color: var(--glass-field) !important;
1040
+ border-color: var(--glass-edge) !important;
1041
+ backdrop-filter: blur(8px);
1042
+ }
1043
+ body.dark .gradio-container {
1044
+ background: var(--bg-page) !important;
1045
+ }
1046
+ /* Blend Gradio's component panels into the page: no boxes, no
1047
+ borders β€” only inputs keep a faint field tint so they stay legible. */
1048
+ body.dark .block,
1049
+ body.dark .form,
1050
+ body.dark .tabs,
1051
+ body.dark .tabitem {
1052
+ background: transparent !important;
1053
+ border-color: transparent !important;
1054
+ box-shadow: none !important;
1055
+ }
1056
+ body.dark .tab-nav {
1057
+ border-bottom: 1px solid var(--border-color) !important;
1058
+ background: transparent !important;
1059
+ }
1060
+ body.dark input, body.dark textarea, body.dark select {
1061
+ background-color: var(--glass-field) !important;
1062
+ color: var(--text-primary) !important;
1063
+ border-color: var(--glass-edge) !important;
1064
+ backdrop-filter: blur(8px);
1065
+ }
1066
+ body.dark label { color: var(--text-secondary) !important; }
1067
+ /* Field labels render as small pills in the Soft theme β€” restyle them
1068
+ as quiet glass chips instead of the default saturated background. */
1069
+ label span[data-testid="block-info"],
1070
+ span.has-info,
1071
+ span[data-testid="block-info"] {
1072
+ background: var(--glass) !important;
1073
+ color: var(--text-primary) !important;
1074
+ border: 1px solid var(--glass-border);
1075
+ border-radius: 9px;
1076
+ padding: 2px 10px;
1077
+ font-weight: 500 !important;
1078
+ backdrop-filter: blur(8px);
1079
+ box-shadow: var(--glass-highlight);
1080
+ }
1081
+ body.dark button:not(.lg) { color: var(--text-primary) !important; }
1082
+ body.dark .footer { color: var(--text-footer) !important; }
1083
+ body.dark details summary { color: var(--text-secondary) !important; }
1084
+ body.dark [data-testid="block-info"] { color: var(--text-primary) !important; }
1085
 
1086
  /* ── Global ──────────────────────────────────────────────────────── */
1087
+ /* Component forms blend into the page in both themes; inputs keep
1088
+ their own field background so they stay clearly interactive. */
1089
+ .gradio-container .form {
1090
+ background: transparent !important;
1091
+ border: none !important;
1092
+ box-shadow: none !important;
1093
+ }
1094
  .gradio-container {
1095
  background: radial-gradient(1200px 500px at 20% -10%, #eef2ff66, transparent 60%),
1096
  radial-gradient(1000px 400px at 90% 10%, #e0f2fe55, transparent 55%),
1097
  var(--bg-page) !important;
1098
  }
1099
+ .gradio-container { max-width: 1024px; margin: 0 auto; }
1100
  .footer { text-align: center; color: var(--text-footer); font-size: 0.85em; padding: 22px 0; }
1101
  details { margin-top: 8px; }
1102
  details summary { cursor: pointer; color: var(--text-secondary); font-weight: 500; }
 
1107
  /* ── Hero ────────────────────────────────────────────────────────── */
1108
  .hero { display: flex; align-items: center; gap: 16px; padding: 8px 0 4px; }
1109
  .hero-icon {
1110
+ font-size: 1.5em; width: 48px; height: 48px; display: flex; align-items: center;
1111
+ justify-content: center; border-radius: 14px;
1112
+ background: var(--glass);
1113
+ border: 1px solid var(--glass-border);
1114
+ box-shadow: var(--glass-highlight);
1115
+ backdrop-filter: blur(12px);
1116
  }
1117
+ .hero-title { margin: 0; font-size: 1.35em; font-weight: 650; letter-spacing: -0.015em; color: var(--text-primary); }
1118
  .hero-sub { margin: 2px 0 0; color: var(--text-muted); font-size: 0.95em; }
1119
 
1120
  /* ── Cards ───────────────────────────────────────────────────────── */
1121
  .ocr-card {
1122
+ background: var(--glass);
1123
+ border: 1px solid var(--glass-border);
1124
  border-radius: var(--radius); padding: 16px 20px; margin-top: 12px;
1125
+ box-shadow: var(--glass-highlight);
1126
+ backdrop-filter: blur(14px);
1127
  }
1128
+ .card-title { font-weight: 600; color: var(--text-primary); margin-bottom: 12px; font-size: 1.0em; letter-spacing: 0.01em; }
1129
  .chips-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
1130
 
1131
  /* ── Chips / badges ──────────────────────────────────────────────── */
1132
  .key-chip {
1133
  display: inline-block; padding: 3px 12px; border-radius: 999px;
1134
+ font-size: 0.82em; font-weight: 500; border: 1px solid var(--glass-border);
1135
+ background: var(--glass); color: var(--text-secondary);
1136
+ backdrop-filter: blur(8px);
1137
  }
1138
+ .key-chip.ok { color: #4ade80; border-color: rgba(74, 222, 128, 0.25); background: rgba(74, 222, 128, 0.07); }
 
1139
  .sev-chip {
1140
  display: inline-block; padding: 3px 12px; border-radius: 999px;
1141
+ font-size: 0.82em; font-weight: 600; border: 1px solid var(--glass-border);
1142
+ background: var(--glass);
1143
  }
1144
 
1145
  /* ── Endpoint cards ──────────────────────────────────────────────── */
1146
  .endpoint-card {
1147
+ border: 1px solid var(--glass-border); border-radius: 12px;
1148
+ padding: 10px 14px; margin-bottom: 8px; background: var(--glass);
1149
+ backdrop-filter: blur(10px);
1150
  }
1151
+ .endpoint-name { font-weight: 600; color: var(--text-primary); display: flex; gap: 8px; align-items: center; }
1152
  .endpoint-badge {
1153
+ font-size: 0.7em; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em;
1154
+ padding: 2px 8px; border-radius: 999px; color: var(--text-muted);
1155
+ background: var(--accent-soft); border: 1px solid var(--glass-border);
1156
  }
1157
  .endpoint-meta { margin-top: 4px; font-size: 0.88em; color: var(--text-secondary); }
1158
 
 
1188
 
1189
  /* ── Theme toggle ���───────────────────────────────────────────────── */
1190
  #theme-toggle-btn {
1191
+ float: right; margin-top: 18px !important; background: var(--glass) !important;
1192
+ border: 1px solid var(--glass-border) !important; border-radius: 10px !important;
1193
  padding: 4px 10px !important; font-size: 1.1em !important; min-width: 44px !important;
1194
+ transition: all 0.2s ease !important;
1195
+ box-shadow: var(--glass-highlight) !important;
1196
+ backdrop-filter: blur(10px) !important;
1197
  }
1198
+ #theme-toggle-btn:hover { background: var(--accent-soft) !important; border-color: var(--glass-edge) !important; }
1199
 
1200
  /* ── Loading spinner ─────────────────────────────────────────────── */
1201
  @keyframes spin { to { transform: rotate(360deg); } }
 
1211
 
1212
  JS_RESTORE_THEME = """
1213
  () => {
1214
+ // Single source of truth for the theme: the body.dark class that
1215
+ // Gradio itself also uses for dark mode. Our own key in localStorage
1216
+ // only records an explicit choice; when absent, whatever Gradio picked
1217
+ // (OS preference) is left untouched.
1218
+ const saved = localStorage.getItem("ocr-theme");
1219
+ if (saved === "dark") document.body.classList.add("dark");
1220
+ if (saved === "light") document.body.classList.remove("dark");
1221
  const btn = document.querySelector("#theme-toggle-btn");
1222
+ if (btn) btn.textContent = document.body.classList.contains("dark") ? "β˜€οΈ" : "πŸŒ™";
1223
  }
1224
  """
1225
 
1226
  JS_TOGGLE_THEME = """
1227
  () => {
1228
+ const isDark = document.body.classList.toggle("dark");
1229
  localStorage.setItem("ocr-theme", isDark ? "dark" : "light");
1230
  const btn = document.querySelector("#theme-toggle-btn");
1231
  if (btn) btn.textContent = isDark ? "β˜€οΈ" : "πŸŒ™";
 
1254
  with gr.Column(scale=4):
1255
  gr.HTML(
1256
  '<div class="hero">'
1257
+ '<div class="hero-icon">β—ˆ</div>'
1258
  '<div>'
1259
  '<h1 class="hero-title">OpenCodeReview</h1>'
1260
  '<p class="hero-sub">AI-powered PR review with human-in-the-loop approval</p>'
1261
  f'<div class="chips-row" style="margin-top:8px">'
1262
+ f'<span class="key-chip ok">{len(_configured_endpoints)} endpoint'
1263
+ f'{"s" if len(_configured_endpoints) != 1 else ""} configured</span>'
1264
+ '<span class="key-chip">Built-ins: Gemini Β· Groq</span>'
1265
+ '<span class="key-chip">Bring your own keys</span>'
1266
  '</div>'
1267
  '</div>'
1268
  '</div>'
 
1278
  # it so review results render immediately instead of waiting on RAGAS.
1279
  ragas_task_state = gr.State(value="")
1280
 
1281
+ # ── Tab: Review ──────────────────────────────────────────────────
1282
+ with gr.Tab("Review"):
1283
  with gr.Row():
1284
  repo_input = gr.Textbox(
1285
  label="Repository",
 
1300
  value="",
1301
  label="LLM Endpoint",
1302
  info=(
1303
+ "Built-ins: Gemini and Groq (Groq serves Llama models). "
1304
+ "Empty = auto (Gemini β†’ Groq fallback)."
1305
  ),
1306
  # Grouped optgroup choices make Gradio's strict membership
1307
  # check reject values that sit inside a group (e.g. a custom
 
1311
  allow_custom_value=True,
1312
  scale=3,
1313
  )
1314
+ test_selected_btn = gr.Button("Test selected", size="sm", scale=1)
1315
  endpoint_test_msg = gr.Markdown()
1316
 
1317
  def on_test_selected(endpoint_name):
1318
  """Probe the currently selected endpoint (built-in or custom)."""
1319
  if not endpoint_name:
1320
  return (
1321
+ "ℹ️ Leave the endpoint empty for auto (Gemini β†’ Groq fallback), "
1322
  "or pick one and test it here."
1323
  )
1324
  from endpoints import get_endpoint
 
1343
  )
1344
 
1345
  # ── Add your own endpoint (BYO key) ─────────────────────────
1346
+ with gr.Accordion("Add a custom endpoint (BYO key)", open=False):
1347
  with gr.Row():
1348
  ep_name_input = gr.Textbox(
1349
  label="Endpoint name",
 
1374
  placeholder="sk-... (stored in memory only, never written to disk)",
1375
  )
1376
  with gr.Row():
1377
+ test_form_btn = gr.Button("Test this endpoint", size="sm")
1378
+ add_endpoint_btn = gr.Button("Save & use endpoint", variant="primary", size="sm")
1379
+ clear_endpoints_btn = gr.Button("Clear added endpoints", size="sm")
1380
  endpoint_save_msg = gr.Markdown()
1381
  session_endpoints_display = gr.HTML(value=_format_session_endpoints())
1382
 
1383
  with gr.Row():
1384
+ run_btn = gr.Button("Run review", variant="primary", size="lg", scale=2)
1385
+ cancel_btn = gr.Button("Cancel", variant="stop", size="lg", visible=False)
1386
 
1387
  loading_box = gr.HTML(
1388
  '<div class="loading-spinner"><div class="spinner"></div>'
 
1399
  ragas_display = gr.HTML()
1400
 
1401
  with gr.Row():
1402
+ approve_btn = gr.Button("Approve & post", variant="primary")
1403
+ reject_btn = gr.Button("Reject", variant="secondary")
1404
 
1405
  resume_msg = gr.Markdown()
1406
 
1407
  # ── Event wiring ──────────────────────────────────────────────
1408
  def on_run_click(*args):
1409
  """Generator that clears old state, runs review, shows results."""
1410
+ # Yield initial loading state β€” must match the 12 outputs of
1411
+ # run_btn.click in order (loading_box, cancel_btn, run_btn,
1412
+ # status_msg, 5 result displays, pr_state, results_panel,
1413
+ # ragas_task_state).
1414
  yield [
1415
  gr.update(visible=True),
1416
  gr.update(visible=True, variant="stop"),
 
1616
  ok, detail = _probe_endpoint(cfg)
1617
  icon = "βœ…" if ok else "❌"
1618
  if ok:
1619
+ return f"{icon} **{name}** (`{model}`) β€” {detail}"
1620
+ return f"{icon} **{name}** β€” {detail}"
1621
 
1622
  test_form_btn.click(
1623
  fn=on_test_form,
 
1631
  outputs=[endpoint_save_msg],
1632
  )
1633
 
1634
+ # ── Tab: Smoke test ──────────────────────────────────────────────
1635
+ with gr.Tab("Smoke test"):
1636
  gr.Markdown(
1637
+ "Run the review pipeline on **synthetic demo data** β€” no API keys needed."
 
1638
  )
1639
  with gr.Row():
1640
+ smoke_btn = gr.Button("Run smoke test", variant="primary", size="lg", scale=2)
1641
+ smoke_cancel_btn = gr.Button("Cancel", variant="stop", size="lg", visible=False)
1642
 
1643
  smoke_loading = gr.HTML(
1644
  '<div class="loading-spinner"><div class="spinner"></div>'
 
1650
  smoke_verdict = gr.HTML()
1651
  smoke_findings = gr.HTML()
1652
  with gr.Row():
1653
+ smoke_approve = gr.Button("Approve (demo)", variant="primary")
1654
+ smoke_reject = gr.Button("Reject (demo)", variant="secondary")
1655
  smoke_resume_msg = gr.Markdown()
1656
 
1657
  smoke_status = gr.Markdown(visible=False)
 
1712
  )
1713
 
1714
  # ── Environment status footer ──────────────────────────────────────
1715
+ with gr.Accordion("Configured keys & health", open=False):
1716
  h = HealthStatus()
1717
  health_data = h.summary()
1718
  gemini_ok = bool(os.environ.get("GEMINI_API_KEY", "").strip())
 
1754
  'as Space secrets to add one.</p>'
1755
  )
1756
  with gr.Row():
1757
+ test_endpoints_btn = gr.Button("Test endpoint connectivity", size="sm", variant="secondary")
1758
  endpoint_test_out = gr.HTML()
1759
  test_endpoints_btn.click(fn=test_endpoints, outputs=[endpoint_test_out])
1760
 
 
1769
  )
1770
 
1771
 
1772
+ def _resolve_port() -> int:
1773
+ """Resolve the listen port from $PORT, falling back to 7860.
1774
+
1775
+ HF Spaces always sets a valid $PORT, but locally the variable may be
1776
+ empty or even 0 (e.g. inherited from an unrelated shell profile) β€”
1777
+ binding port 0 makes Gradio's post-launch self-check fail with a
1778
+ confusing connection traceback, so invalid values are rejected here.
1779
+ """
1780
+ raw = (os.environ.get("PORT") or "").strip()
1781
+ try:
1782
+ port = int(raw) if raw else 7860
1783
+ except ValueError:
1784
+ logger.warning("Ignoring non-numeric PORT=%r β€” using 7860", raw)
1785
+ return 7860
1786
+ if not 1 <= port <= 65535:
1787
+ logger.warning("Ignoring out-of-range PORT=%d β€” using 7860", port)
1788
+ return 7860
1789
+ return port
1790
+
1791
+
1792
  def main() -> None:
1793
+ port = _resolve_port()
1794
  # Gradio 6: theme/css moved from the Blocks constructor to launch().
1795
  demo.queue(max_size=10).launch(
1796
  server_name="0.0.0.0",
eval_data/ragas_eval.py CHANGED
@@ -28,6 +28,8 @@ from __future__ import annotations
28
 
29
  import logging
30
  import os
 
 
31
  from typing import Any, Optional
32
 
33
  logger = logging.getLogger(__name__)
@@ -58,6 +60,93 @@ def _check_ragas() -> bool:
58
  return _RAGAS_AVAILABLE
59
 
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  def _get_evaluator_llm(endpoint: Optional[str] = None):
62
  """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
63
 
@@ -82,26 +171,30 @@ def _get_evaluator_llm(endpoint: Optional[str] = None):
82
 
83
  llm = create_llm(endpoint=endpoint, temperature=0)
84
  logger.info("RAGAS evaluator: using custom endpoint %s", endpoint)
85
- return LangchainLLMWrapper(llm)
86
 
87
  from llm_factory import _get_groq_chat, _get_gemini_chat
88
 
89
- llm = _get_groq_chat(temperature=0)
 
 
 
90
  if llm is None:
91
  logger.info(
92
  "RAGAS evaluator: GROQ_API_KEY not set β€” falling back to Gemini"
93
  )
94
- llm = _get_gemini_chat(temperature=0)
95
  if llm is None:
96
  raise ValueError(
97
  "No LLM available for RAGAS scoring. "
98
  "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
99
  )
100
  logger.info(
101
- "RAGAS evaluator: using %s",
102
  type(llm).__name__,
 
103
  )
104
- return LangchainLLMWrapper(llm)
105
  except ValueError as exc:
106
  logger.warning("RAGAS evaluator: %s", exc)
107
  raise RuntimeError(
@@ -392,6 +485,11 @@ def _compute_mmr(
392
  # LangchainLLMWrapper stores the model as .langchain_llm in ragas
393
  # 0.4.x and as .llm in 0.3.x β€” accept both.
394
  langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
 
 
 
 
 
395
  raw = langchain_model.invoke(prompt)
396
  response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
397
  if response_text.startswith("Y"):
 
28
 
29
  import logging
30
  import os
31
+ import threading
32
+ import time
33
  from typing import Any, Optional
34
 
35
  logger = logging.getLogger(__name__)
 
60
  return _RAGAS_AVAILABLE
61
 
62
 
63
+ # Seconds to sleep before every RAGAS LLM call. RAGAS scoring fires a
64
+ # burst of ~20-30 model calls per review (context-precision judgments,
65
+ # faithfulness verification, answer relevancy, MMR relevance checks).
66
+ # Spacing them keeps the burst under Groq/Gemini free-tier per-minute rate
67
+ # limits so scoring completes instead of tripping 429s β€” which previously
68
+ # caused long retry backoffs and 0.0000 scores. Override with the
69
+ # OCR_RAGAS_INTERVAL env var (float seconds, 0 disables).
70
+ _RAGAS_INTERVAL = float(os.environ.get("OCR_RAGAS_INTERVAL", "3.0") or 3.0)
71
+ _ragas_throttle_lock = threading.Lock()
72
+
73
+
74
+ class _ThrottledChatModel:
75
+ """Wrap a LangChain chat model so every underlying API call RAGAS makes
76
+ is spaced by a fixed interval.
77
+
78
+ RAGAS's ``LangchainLLMWrapper`` (deprecated shim in 0.4.x, forwards to
79
+ the langchain model) and the custom MMR path call the model through
80
+ different entry points (sync/async, single/batched). Intercepting
81
+ ``invoke`` / ``generate`` / ``ainvoke`` / ``agenerate`` here guarantees
82
+ every request is throttled regardless of ragas version.
83
+ """
84
+
85
+ def __init__(self, model, interval: float | None = None):
86
+ self._model = model
87
+ self._interval = _RAGAS_INTERVAL if interval is None else interval
88
+
89
+ def _wait(self) -> None:
90
+ if self._interval > 0:
91
+ with _ragas_throttle_lock:
92
+ time.sleep(self._interval)
93
+
94
+ # ── Sync entry points ───────────────────────────────────────────────
95
+ def invoke(self, *args, **kwargs):
96
+ self._wait()
97
+ return self._model.invoke(*args, **kwargs)
98
+
99
+ def generate(self, messages, *args, **kwargs):
100
+ # Serialize LangChain batch calls into individual throttled
101
+ # requests so every underlying API call is spaced by the interval.
102
+ if (
103
+ isinstance(messages, list)
104
+ and messages
105
+ and isinstance(messages[0], list)
106
+ ):
107
+ from langchain_core.outputs import Generation, LLMResult
108
+
109
+ generations = []
110
+ for msgs in messages:
111
+ self._wait()
112
+ # invoke() does not accept callbacks/run_manager/config that
113
+ # ragas may forward to generate() β€” drop them here.
114
+ resp = self._model.invoke(msgs)
115
+ text = resp.content if hasattr(resp, "content") else str(resp)
116
+ generations.append([Generation(text=text, message=resp)])
117
+ return LLMResult(generations=generations, llm_output=None)
118
+ self._wait()
119
+ return self._model.generate(messages, *args, **kwargs)
120
+
121
+ # ── Async entry points ──────────────────────────────────────────────
122
+ async def ainvoke(self, *args, **kwargs):
123
+ self._wait()
124
+ return await self._model.ainvoke(*args, **kwargs)
125
+
126
+ async def agenerate(self, messages, *args, **kwargs):
127
+ if (
128
+ isinstance(messages, list)
129
+ and messages
130
+ and isinstance(messages[0], list)
131
+ ):
132
+ from langchain_core.outputs import Generation, LLMResult
133
+
134
+ generations = []
135
+ for msgs in messages:
136
+ self._wait()
137
+ # Same kwargs caveat as generate(): ainvoke has no callbacks.
138
+ resp = await self._model.ainvoke(msgs)
139
+ text = resp.content if hasattr(resp, "content") else str(resp)
140
+ generations.append([Generation(text=text, message=resp)])
141
+ return LLMResult(generations=generations, llm_output=None)
142
+ self._wait()
143
+ return await self._model.agenerate(messages, *args, **kwargs)
144
+
145
+ # ── Everything else passes through ──────────────────────────────────
146
+ def __getattr__(self, name: str):
147
+ return getattr(self._model, name)
148
+
149
+
150
  def _get_evaluator_llm(endpoint: Optional[str] = None):
151
  """Return a RAGAS-compatible LLM, reusing the project's LLM factory.
152
 
 
171
 
172
  llm = create_llm(endpoint=endpoint, temperature=0)
173
  logger.info("RAGAS evaluator: using custom endpoint %s", endpoint)
174
+ return LangchainLLMWrapper(_ThrottledChatModel(llm))
175
 
176
  from llm_factory import _get_groq_chat, _get_gemini_chat
177
 
178
+ # max_retries=5: residual 429s (rate limit) retry instead of failing
179
+ # a metric; combined with the throttle below, the burst stays under
180
+ # the provider's per-minute limit so retries are the exception.
181
+ llm = _get_groq_chat(temperature=0, max_retries=5)
182
  if llm is None:
183
  logger.info(
184
  "RAGAS evaluator: GROQ_API_KEY not set β€” falling back to Gemini"
185
  )
186
+ llm = _get_gemini_chat(temperature=0, max_retries=5)
187
  if llm is None:
188
  raise ValueError(
189
  "No LLM available for RAGAS scoring. "
190
  "Set GROQ_API_KEY (preferred) or GEMINI_API_KEY."
191
  )
192
  logger.info(
193
+ "RAGAS evaluator: using %s (throttled %ss)",
194
  type(llm).__name__,
195
+ _RAGAS_INTERVAL,
196
  )
197
+ return LangchainLLMWrapper(_ThrottledChatModel(llm))
198
  except ValueError as exc:
199
  logger.warning("RAGAS evaluator: %s", exc)
200
  raise RuntimeError(
 
485
  # LangchainLLMWrapper stores the model as .langchain_llm in ragas
486
  # 0.4.x and as .llm in 0.3.x β€” accept both.
487
  langchain_model = getattr(llm, "langchain_llm", None) or getattr(llm, "llm", None)
488
+ # Space the relevance judgments too β€” this unwrapped path bypasses
489
+ # the model wrapper on some ragas versions, so sleep explicitly
490
+ # (unless the wrapper is already in the path, to avoid double-sleep).
491
+ if not isinstance(langchain_model, _ThrottledChatModel):
492
+ time.sleep(_RAGAS_INTERVAL)
493
  raw = langchain_model.invoke(prompt)
494
  response_text = raw.content.strip().upper() if hasattr(raw, "content") else str(raw).strip().upper()
495
  if response_text.startswith("Y"):
opencodereview-spec.md ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OpenCodeReview β€” Project Description
2
+
3
+ > **Spec file** Β· Audience: future maintainers & contributors Β· Goal: balanced
4
+ > overview (features + architecture + how to run) Β· Accuracy: **as-is**, i.e. the
5
+ > working tree is the source of truth, including uncommitted changes. No
6
+ > recommendations section β€” this document describes only.
7
+ >
8
+ > Written: 2026-08-12 Β· Based on code reading (no commands executed).
9
+
10
+ ---
11
+
12
+ ## 1. What the project is
13
+
14
+ **OpenCodeReview** is an AI-powered pull-request reviewer with a
15
+ **human-in-the-loop** approval gate. It runs a LangGraph pipeline in which three
16
+ specialist LLM reviewers β€” **correctness**, **security**, and **test coverage** β€”
17
+ analyze a PR in parallel, grounded by a ChromaDB vector store over the repo's
18
+ codebase history. Nothing is posted to GitHub until a human reviews the verdict
19
+ and explicitly approves it. Findings are posted as inline PR review comments with
20
+ an automatic fallback to issue-level comments when lines go stale.
21
+
22
+ It ships as both a **Click CLI** (`main.py`) and a **Gradio web UI** (`app.py`,
23
+ the entry point for Hugging Face Spaces), and includes an evaluation harness
24
+ (ground-truth precision/recall/F1 + RAGAS retrieval metrics), optional
25
+ observability (LangSmith + Langfuse), cost/TTFT tracking, a health-check CLI
26
+ (`doctor`), and a continuous alerting script.
27
+
28
+ **One-paragraph elevator summary:** "Enter `owner/repo` + PR number (or run the
29
+ CLI), the pipeline fetches the PR, indexes/retrieves relevant code context,
30
+ runs three parallel LLM reviews, dedupes and scores the findings, pauses for a
31
+ human decision, and only then posts comments back to GitHub."
32
+
33
+ ---
34
+
35
+ ## 2. Feature summary
36
+
37
+ - **Three parallel specialist reviewers** β€” correctness, security, and
38
+ test-coverage nodes run concurrently on the same diff, each with its own
39
+ versioned system prompt under `prompts/`.
40
+ - **Retrieval-augmented review** β€” a persistent ChromaDB store embeds the repo's
41
+ source, up to 20 past merged PRs, and docs (README, CONTRIBUTING…); the diff is
42
+ used as a query and the top ~15 chunks are injected as reviewer context.
43
+ - **Human-in-the-loop approval** β€” the graph calls LangGraph's `interrupt()` and
44
+ pauses; the caller (CLI prompt or UI buttons) resumes with `approve` / `reject`.
45
+ - **Inline comments** β€” approved findings are posted at the exact file/line
46
+ position; a GitHub `422` (stale line) triggers an issue-comment fallback.
47
+ - **Smart aggregation** β€” heuristic deduplication (file/line proximity Β±5 lines +
48
+ confidence) and noise filtering (< 0.25 confidence dropped), plus a rule-based
49
+ verdict with an optional LLM-critic pass.
50
+ - **LLM flexibility** β€” Gemini primary β†’ Groq fallback, plus **custom endpoints**
51
+ (BYO keys) for any OpenAI-compatible API, Anthropic, or Google, configured via
52
+ `OCR_ENDPOINT_*` env vars or added at runtime in the UI.
53
+ - **Evaluation & observability** β€” ground-truth eval harness, RAGAS retrieval
54
+ metrics, LangSmith/Langfuse tracing, per-run token cost & TTFT.
55
+ - **CLI + Web UI** β€” identical pipeline driven from either interface.
56
+ - **GitHub OAuth Device Flow** β€” interactive login, tokens stored in the OS
57
+ keyring (priority: keyring β†’ `GITHUB_TOKEN` env).
58
+
59
+ ---
60
+
61
+ ## 3. System architecture (pipeline-focused)
62
+
63
+ The system is a **LangGraph state machine** (`graph.py`) with a typed Pydantic
64
+ state schema and SQLite checkpointing. Topology:
65
+
66
+ ```
67
+ START β†’ ingestion β†’ retrieval ──→ correctness_review ──┐
68
+ β”œβ”€β”€β†’ security_review β”œβ”€β”€β†’ aggregator β†’ human_approval (interrupt ⏸) β†’ executor β†’ END
69
+ └──→ test_coverage_review β”€β”€β”˜
70
+ ```
71
+
72
+ ### 3.1 Pipeline nodes
73
+
74
+ | # | Node | Module | What it does |
75
+ |---|------|--------|--------------|
76
+ | 1 | `ingestion` | `nodes/ingestion.py` | Fetches PR metadata, the full unified diff, and per-file contents from the GitHub API (handles fork PRs, pagination, rate limits). No-op when a diff is already present in state (e.g. synthetic payloads). |
77
+ | 2 | `retrieval` | `nodes/retrieval.py` | Builds/loads a ChromaDB collection embedding the repo source, past merged PRs, and docs; queries it with the diff; returns top-15 context chunks. Cached per base-branch SHA so embeddings aren't rebuilt per run. |
78
+ | 3–5 | `correctness_review`, `security_review`, `test_coverage_review` | `nodes/{correctness,security,test_coverage}_reviewer.py` | Three parallel LLM reviewers. Each emits Pydantic-validated findings (category, severity, confidence, line range, suggested fix) via `with_structured_output`. Prompts live in `prompts/*_v1.txt`. |
79
+ | 6 | `aggregator` | `nodes/aggregator.py` | Merges findings pointing at the same file/line (Β±5 lines, highest confidence wins), drops noise below 0.25, then produces a verdict. Default is a rule-based verdict (~10 ms, zero LLM cost); `AGGREGATOR_USE_LLM_CRITIC=true` enables an optional LLM critic pass. |
80
+ | 7 | `human_approval` | `nodes/human_approval.py` | Calls `interrupt()` β€” the graph **pauses** and returns verdict + findings to the caller. Nothing is posted until resumed with `approve` / `reject`. |
81
+ | 8 | `executor` | `nodes/executor.py` | Posts each finding as an inline PR review comment (multi-line ranges supported). On GitHub `422` (stale line), falls back to a general issue comment. Posts the overall verdict as a summary comment. |
82
+
83
+ **Verdict rules (rule-based default):**
84
+
85
+ | Condition | Recommendation | Approved |
86
+ |---|---|---|
87
+ | β‰₯ 1 critical finding | `block` | ❌ |
88
+ | β‰₯ 1 high finding | `request_changes` | ❌ |
89
+ | any medium/low/info finding | `comment` | βœ… |
90
+ | no findings | `approve` | βœ… |
91
+
92
+ Score = `10 βˆ’ 4Β·critical βˆ’ 2Β·high βˆ’ 0.5Β·medium`, clamped to 0–10.
93
+
94
+ ### 3.2 State schema (minimal)
95
+
96
+ `OpenCodeReviewState` (`state.py`) is a Pydantic `BaseModel`. Key fields:
97
+
98
+ - PR metadata: `repo`, `pr_number`, `base_sha`, `diff`, `changed_files`
99
+ - `endpoint` β€” chosen custom LLM endpoint name (empty = built-in default)
100
+ - Accumulated lists (`Annotated[list, add]` reducers so parallel branches merge):
101
+ `context_chunks`, `findings`
102
+ - Aggregated output: `final_findings`, `verdict` (`Verdict` model), `human_approved`
103
+
104
+ Sub-models: `ChangedFile`, `ContextChunk`, `Finding`, `Verdict`, and a `Severity`
105
+ enum (`critical`/`high`/`medium`/`low`/`info`). See `state.py` for field-level
106
+ detail.
107
+
108
+ ### 3.3 Checkpointing & resume
109
+
110
+ - Every run is persisted via **`SqliteSaver`** on a SQLite DB
111
+ (`graph.py`, `checkpoints.db` by default; `:memory:` for ephemeral runs).
112
+ - A `JsonPlusSerializer` with an allowlist of the Pydantic models handles state
113
+ (de)serialization.
114
+ - The compiled graph exposes `_opencodereview_conn` (informal handle) so callers
115
+ close the SQLite connection when a run finishes β€” prevents file-handle leaks in
116
+ the long-running UI. The DB file is cleaned up after runs (`_cleanup_db()`).
117
+ - Because checkpoints persist to disk, a paused graph can be resumed after a page
118
+ reload or process restart via the same `thread_id`.
119
+
120
+ ---
121
+
122
+ ## 4. Supporting layers
123
+
124
+ ### 4.1 LLM layer (`llm_factory.py`)
125
+
126
+ - **Default chain:** Google Gemini (`gemini-3.1-flash-lite`, primary) β†’ Groq
127
+ (`llama-3.3-70b-versatile`, fallback); `temperature=0`. `ValueError` if no key.
128
+ - **Custom endpoints** (`endpoints.py` + `llm_factory.create_endpoint_llm`):
129
+ - OpenAI-compatible (`langchain-openai`) β€” DeepSeek, OpenRouter, vLLM, Ollama,
130
+ Together, local proxies…
131
+ - Anthropic (`langchain-anthropic`), Google (`langchain-google-genai`).
132
+ - **Endpoint registry** (`endpoints.py`):
133
+ - Env convention: `OCR_ENDPOINT_<n>_NAME/TYPE/API_KEY/BASE_URL/MODEL`
134
+ (`TYPE`: `openai` | `anthropic` | `google`; default `openai`).
135
+ - Built-in entries: `Gemini` and `Grok` are always selectable as endpoints.
136
+ - UI-added endpoints live in an in-memory, thread-locked session registry
137
+ (never written to disk; vanish on process restart).
138
+ - Name precedence on collision: **session (UI) > env-var > built-in**.
139
+ - Keys are only read from the environment and masked for display.
140
+
141
+ ### 4.2 GitHub integration (`github_client.py`, `auth.py`)
142
+
143
+ - `requests`-based client; token resolution priority **keyring β†’ `GITHUB_TOKEN`
144
+ env**; 401 detection with a helpful re-auth error.
145
+ - HTTP caching via `requests-cache` (15-min TTL) under `.opencodereview/`.
146
+ - `auth.py`: GitHub OAuth **Device Flow** β€” `auth login` prints a one-time code;
147
+ token stored in the OS keyring (scope `repo`).
148
+
149
+ ### 4.3 Aggregation & verdict (see Β§3.1 node 6)
150
+
151
+ ### 4.4 Configuration (`config.py`)
152
+
153
+ - `Settings` (pydantic-settings) resolves env var β†’ system keyring β†’ error.
154
+ - Provider registry currently covers `anthropic` (`OPENCODEREVIEW_ANTHROPIC_KEY`).
155
+ - CLI: `config set-key`, `config show` (masked), `config set-observability`.
156
+
157
+ ---
158
+
159
+ ## 5. Interfaces & configuration
160
+
161
+ ### 5.1 CLI (`main.py`)
162
+
163
+ | Command | Purpose |
164
+ |---|---|
165
+ | `review [--smoke] [--repo OWNER/REPO] [--pr N] [--endpoint NAME]` | Run the pipeline. Default repo/pr uses a built-in synthetic payload (no keys/network needed). Interactive HITL prompt (`a`/`r`/`q`). |
166
+ | `doctor` | Health checks: Python version, API keys, LLM endpoints, Groq/Langfuse connectivity. |
167
+ | `auth login/status/logout` | GitHub OAuth Device Flow management. |
168
+ | `config …` | `set-key`, `show`, `set-observability` (see Β§4.4). |
169
+
170
+ Every option also works as an env var with the `OCR_` prefix
171
+ (e.g. `--repo` β†’ `OCR_REPO`, `--pr` β†’ `OCR_PR_NUMBER`).
172
+
173
+ ### 5.2 Gradio web UI (`app.py`)
174
+
175
+ - **Review a PR** tab (owner/repo + PR number, live pipeline status, then
176
+ **Approve & Post** / **Reject**).
177
+ - **Smoke Test** tab (synthetic demo, no keys).
178
+ - Severity-colored findings table, verdict card, RAGAS retrieval-quality bars,
179
+ per-run cost summary.
180
+ - **Configured Keys & Health** accordion; dark/light theme toggle (persisted).
181
+ - **LLM Endpoint** dropdown with a "Built-in" optgroup (Gemini, Grok) and flat
182
+ custom-endpoint entries; an add-any-custom-endpoint form (BYO name/type/base
183
+ URL/key/model); endpoint test buttons that probe connectivity
184
+ (`_probe_endpoint` β€” classifies 401/403 as "server rejected the key", falls
185
+ back to a `chat/completions` probe when `GET /models` is blocked/missing).
186
+
187
+ ### 5.3 Environment variables (key ones; full list in README)
188
+
189
+ | Variable | Purpose |
190
+ |---|---|
191
+ | `GEMINI_API_KEY` / `GROQ_API_KEY` | Primary / fallback LLM keys |
192
+ | `GITHUB_TOKEN` | GitHub token (keyring preferred) |
193
+ | `OCR_ENDPOINT_<n>_*` | Custom endpoint configs (name/type/key/base_url/model) |
194
+ | `AGGREGATOR_USE_LLM_CRITIC` | `true` enables LLM-critic aggregation pass |
195
+ | `LANGSMITH_API_KEY`, `LANGFUSE_*` | Observability backends |
196
+ | `PORT` | Gradio port (default 7860) |
197
+ | `OCR_RAGAS_INTERVAL` | RAGAS throttle interval in seconds (default 3.0; 0 disables) |
198
+
199
+ ---
200
+
201
+ ## 6. Evaluation & observability
202
+
203
+ ### 6.1 Ground-truth evaluation (`eval_data/`)
204
+
205
+ - `fetcher.py` builds `prs.jsonl` β€” one JSON per PR with diff, changed files, and
206
+ human review comments as ground truth (requires `GITHUB_TOKEN`).
207
+ - `evaluate.py` matches findings to human comments by **file path + line
208
+ proximity (Β±3 lines)** (optional keyword-overlap bonus), computes
209
+ **precision / recall / F1** per PR plus micro/macro averages β†’
210
+ `eval_data/eval_results.json`. Refuses to run while `GITHUB_TOKEN` is set
211
+ (executor would post to real PRs) unless `--force`.
212
+ - `ragas_eval.py` computes RAGAS retrieval metrics: `context_precision`,
213
+ `context_recall`, `faithfulness`, `answer_relevancy`, `mmr`.
214
+
215
+ ### 6.2 Observability (`observability.py`)
216
+
217
+ - **LangSmith** β€” enabled automatically when `LANGSMITH_API_KEY` (or legacy
218
+ `LANGCHAIN_API_KEY`) is set.
219
+ - **Langfuse** β€” enabled when public+secret keys are set; a trace per review;
220
+ scores logged: `verdict_score`, `findings_count`, `ragas_*` metrics.
221
+ - **Cost & TTFT** β€” `TokenCostCallback` tracks per-run USD cost (via a
222
+ `MODEL_PRICING` table covering Groq models and Gemini) and time-to-first-token;
223
+ printed by CLI and shown in the UI.
224
+ - **Health checks** β€” `HealthStatus`, `check_groq_connectivity`,
225
+ `check_langfuse_connectivity` (used by `doctor`).
226
+
227
+ ### 6.3 RAGAS details worth knowing
228
+
229
+ - RAGAS scoring is routed **Groq-first** (avoids Gemini's ~15 req/min quota),
230
+ then Gemini. Requires `GROQ_API_KEY` or `GEMINI_API_KEY`.
231
+ - Uncommitted work in the working tree throttles RAGAS LLM calls through a
232
+ `_ThrottledChatModel` wrapper (`OCR_RAGAS_INTERVAL`, default 3 s between calls)
233
+ to stay under free-tier per-minute rate limits, and failed metrics are logged
234
+ as `None` (not fake `0.0`), with consumers guarded against `None`.
235
+
236
+ ### 6.4 Alerting (`scripts/alert.py`)
237
+
238
+ Runs the smoke-test review, compares the score to a stored baseline, and pings a
239
+ **Discord or Slack webhook** when the score deviates by > 2.5 points or the run
240
+ fails. `alert.yml` runs it every 6 hours.
241
+
242
+ ---
243
+
244
+ ## 7. Deployment & CI
245
+
246
+ - **Dockerfile** β€” multi-stage: `builder` β†’ `runtime` (default; ONNX MiniLM
247
+ embedder, no PyTorch) β†’ `runtime-full` (adds sentence-transformers/PyTorch).
248
+ - **docker-compose.yml** β€” one service, named volume for the vector store
249
+ (`opencodereview_vectors`) so embeddings persist across runs;
250
+ `docker-entrypoint.sh` fixes volume permissions and drops to a non-root user.
251
+ - **Hugging Face Spaces** β€” `.github/workflows/deploy-hf.yml` syncs the repo to
252
+ the Space and restarts it (Docker SDK, port 7860) on push to `main`.
253
+ - **GitHub Actions** β€” `alert.yml` (every-6h smoke-test alert).
254
+
255
+ ---
256
+
257
+ ## 8. Project structure (file map)
258
+
259
+ ```
260
+ β”œβ”€β”€ app.py # Gradio web UI (HF Spaces entry point)
261
+ β”œβ”€β”€ main.py # Click CLI β€” review / doctor / auth / config
262
+ β”œβ”€β”€ graph.py # LangGraph pipeline + SqliteSaver checkpointing
263
+ β”œβ”€β”€ state.py # Typed Pydantic state schema
264
+ β”œβ”€β”€ llm_factory.py # Gemini β†’ Groq fallback + custom-endpoint factory
265
+ β”œβ”€β”€ endpoints.py # Custom LLM endpoint registry (env + UI session)
266
+ β”œβ”€β”€ github_client.py # GitHub API client, token resolution, HTTP cache
267
+ β”œβ”€β”€ auth.py # GitHub OAuth Device Flow
268
+ β”œβ”€β”€ config.py # Settings (env β†’ keyring β†’ error) + config CLI
269
+ β”œβ”€β”€ observability.py # LangSmith/Langfuse, cost & TTFT, health checks
270
+ β”œβ”€β”€ nodes/ # One module per graph node (8 nodes)
271
+ β”œβ”€β”€ prompts/ # Versioned system prompts (…_v1.txt)
272
+ β”œβ”€β”€ eval_data/ # fetcher.py Β· evaluate.py Β· ragas_eval.py Β· prs.jsonl Β· eval_results.json
273
+ β”œβ”€β”€ scripts/alert.py # Continuous health monitor (Discord/Slack)
274
+ β”œβ”€β”€ .github/workflows/ # alert.yml Β· deploy-hf.yml
275
+ └── Dockerfile Β· docker-compose.yml Β· docker-entrypoint.sh
276
+ ```
277
+
278
+ ---
279
+
280
+ ## 9. Current state β€” known gaps & observations
281
+
282
+ These are the honest as-is observations a maintainer should know (no
283
+ recommendations here β€” just description):
284
+
285
+ - **No automated tests.** There is no `tests/` directory; verification relies on
286
+ `python main.py review --smoke`, `python main.py doctor`, and the eval harness.
287
+ The README acknowledges this.
288
+ - **Breadth-first exception swallowing.** Many layers catch `Exception` and only
289
+ warn or silently degrade: Langfuse score logging, reviewer nodes (LLM failure β†’
290
+ empty review), the aggregator's optional LLM critic, and RAGAS metric failures.
291
+ This historically hid real failures (documented in `FIXES.md`).
292
+ - **FIXES.md backlog** β€” 14 documented fixes, most already applied to the code
293
+ (verified: `import requests` in `nodes/executor.py`, the `_opencodereview_conn`
294
+ connection-close pattern in `graph.py`/`main.py`/`app.py`, deleted dead
295
+ `passthrough`/`post_results` nodes, and a `MODEL_PRICING` table incl. Gemini).
296
+ The master checklist at the end of `FIXES.md` is unchecked β€” treat it as a
297
+ record of intent rather than current status.
298
+ - **Uncommitted working-tree changes** (described as current state above):
299
+ - `app.py` β€” improved endpoint probing (401/403 classified as key-rejected,
300
+ chat/completions fallback probe for servers without `GET /models`, clearer
301
+ status text in cards and the test form).
302
+ - `eval_data/ragas_eval.py` β€” `_ThrottledChatModel` rate-limit throttle,
303
+ Groq-first with `max_retries=5`, failed metrics β†’ `None`.
304
+ - **Minor artifacts:** a stray `nodes__init__.py` file sits at the repo root
305
+ (an accidental duplicate of `nodes/__init__.py`); `.opencodereview/vectors/`
306
+ contains a large checked-in ChromaDB sqlite file.
307
+ - **Naming inconsistencies:** the UI/CLI refer to the built-in Groq provider as
308
+ "Grok" (`builtin_endpoints()`), which differs from the actual provider name.
309
+ - **`nodes/aggregator.py`** (unlike the reviewers) imports a shared
310
+ `GROQ_MODEL`-style constant rather than a centralised `constants.py` β€” there is
311
+ no `constants.py`; constants are still duplicated across modules.
312
+
313
+ ---
314
+
315
+ ## 10. How to run it (quick reference)
316
+
317
+ ```bash
318
+ pip install -r requirements.txt
319
+ export GITHUB_TOKEN=ghp_... # real PRs only; keyring preferred
320
+ export GEMINI_API_KEY=AIza... # or GROQ_API_KEY
321
+
322
+ python main.py review --smoke # offline pipeline check
323
+ python main.py review --repo psf/requests --pr 42 # real PR
324
+ python main.py review --endpoint DeepSeek ... # custom endpoint
325
+ python main.py doctor # health checks
326
+ python app.py # web UI at :7860
327
+
328
+ python eval_data/evaluate.py --max-prs 2 # quick eval run
329
+ python eval_data/ragas_eval.py --data eval_data/prs.jsonl # RAGAS metrics
330
+ ```
331
+
332
+ ---
333
+
334
+ *End of project description. Source of truth: the working tree at commit
335
+ `bd08fdb` + uncommitted changes, verified by code reading on 2026-08-12.*