Sdm0 commited on
Commit
9549f70
Β·
verified Β·
1 Parent(s): 73bf7d1

Deploy 396d7815

Browse files
Files changed (2) hide show
  1. app.py +131 -4
  2. endpoints.py +104 -6
app.py CHANGED
@@ -41,7 +41,13 @@ from observability import (
41
  check_groq_connectivity,
42
  check_langfuse_connectivity,
43
  )
44
- from endpoints import discover_endpoints
 
 
 
 
 
 
45
  from state import Verdict
46
 
47
  import subprocess
@@ -444,6 +450,29 @@ def _format_run_summary(
444
  )
445
 
446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
  def _probe_endpoint(ep) -> tuple[bool, str]:
448
  """Quick connectivity probe for a custom endpoint (no LLM generation)."""
449
  import urllib.request as _ur
@@ -959,14 +988,51 @@ with gr.Blocks(title="OpenCodeReview") as demo:
959
  value="",
960
  label="LLM Endpoint",
961
  info=(
962
- "Run the review on a custom model (OpenAI-compatible / "
963
- "Anthropic / Google). Empty = built-in default."
964
  if _endpoint_choices
965
- else "No custom endpoints configured β€” set OCR_ENDPOINT_* secrets to add one."
966
  ),
967
  scale=3,
968
  )
969
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970
  with gr.Row():
971
  run_btn = gr.Button("β–Ά Run Review", variant="primary", size="lg", scale=2)
972
  cancel_btn = gr.Button("⏹ Cancel", variant="stop", size="lg", visible=False)
@@ -1072,6 +1138,67 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1072
  outputs=[resume_msg],
1073
  )
1074
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1075
  # ── Tab: Smoke Test ──────────────────────────────────────────────────
1076
  with gr.Tab("Smoke Test"):
1077
  gr.Markdown(
 
41
  check_groq_connectivity,
42
  check_langfuse_connectivity,
43
  )
44
+ from endpoints import (
45
+ clear_session_endpoints,
46
+ discover_endpoints,
47
+ endpoint_choices,
48
+ register_endpoint,
49
+ session_endpoints,
50
+ )
51
  from state import Verdict
52
 
53
  import subprocess
 
450
  )
451
 
452
 
453
+ def _format_session_endpoints() -> str:
454
+ """Render cards for endpoints added at runtime via the UI form."""
455
+ eps = session_endpoints()
456
+ if not eps:
457
+ return (
458
+ '<p class="muted small">No endpoints added in this session yet β€” '
459
+ "fill the form above and click <b>Save & use endpoint</b>.</p>"
460
+ )
461
+ cards = "".join(
462
+ f'<div class="endpoint-card">'
463
+ f'<div class="endpoint-name">{html.escape(ep.name)}'
464
+ f'<span class="endpoint-badge">{ep.provider}</span></div>'
465
+ f'<div class="endpoint-meta"><code>{html.escape(ep.model)}</code>'
466
+ f' Β· {html.escape(ep.base_url or "default URL")} Β· key {ep.masked_key}</div>'
467
+ f'</div>'
468
+ for ep in eps
469
+ )
470
+ return (
471
+ f'<div class="card-title" style="margin:6px 0 6px">'
472
+ f'Added in this session ({len(eps)})</div><div>{cards}</div>'
473
+ )
474
+
475
+
476
  def _probe_endpoint(ep) -> tuple[bool, str]:
477
  """Quick connectivity probe for a custom endpoint (no LLM generation)."""
478
  import urllib.request as _ur
 
988
  value="",
989
  label="LLM Endpoint",
990
  info=(
991
+ "Pick a saved endpoint, or add your own below. "
992
+ "Empty = built-in default."
993
  if _endpoint_choices
994
+ else "No endpoints yet β€” add one below or set OCR_ENDPOINT_* secrets."
995
  ),
996
  scale=3,
997
  )
998
 
999
+ # ── Add your own endpoint (BYO key) ─────────────────────────
1000
+ with gr.Accordion("βž• Add custom endpoint (BYO key)", open=False):
1001
+ with gr.Row():
1002
+ ep_name_input = gr.Textbox(
1003
+ label="Endpoint name",
1004
+ placeholder="e.g. My DeepSeek",
1005
+ scale=1,
1006
+ )
1007
+ ep_type_input = gr.Dropdown(
1008
+ choices=["openai", "anthropic", "google"],
1009
+ value="openai",
1010
+ label="Type",
1011
+ info="openai = any OpenAI-compatible API (DeepSeek, OpenRouter, Ollama…)",
1012
+ scale=1,
1013
+ )
1014
+ with gr.Row():
1015
+ ep_base_url_input = gr.Textbox(
1016
+ label="API endpoint (base URL)",
1017
+ placeholder="https://api.deepseek.com/v1 (optional for google)",
1018
+ scale=2,
1019
+ )
1020
+ ep_model_input = gr.Textbox(
1021
+ label="Model",
1022
+ placeholder="deepseek-chat / claude-sonnet-4-20250514 / gemini-3.1-flash",
1023
+ scale=2,
1024
+ )
1025
+ ep_api_key_input = gr.Textbox(
1026
+ label="API key",
1027
+ type="password",
1028
+ placeholder="sk-... (stored in memory only, never written to disk)",
1029
+ )
1030
+ with gr.Row():
1031
+ add_endpoint_btn = gr.Button("πŸ’Ύ Save & use endpoint", variant="primary", size="sm")
1032
+ clear_endpoints_btn = gr.Button("πŸ—‘ Clear added endpoints", size="sm")
1033
+ endpoint_save_msg = gr.Markdown()
1034
+ session_endpoints_display = gr.HTML(value=_format_session_endpoints())
1035
+
1036
  with gr.Row():
1037
  run_btn = gr.Button("β–Ά Run Review", variant="primary", size="lg", scale=2)
1038
  cancel_btn = gr.Button("⏹ Cancel", variant="stop", size="lg", visible=False)
 
1138
  outputs=[resume_msg],
1139
  )
1140
 
1141
+ # ── Add / clear custom endpoints ─────────────────────────────
1142
+ def on_add_endpoint(name, ptype, base_url, api_key, model):
1143
+ """Register the form values, refresh the dropdown, auto-select."""
1144
+ try:
1145
+ cfg = register_endpoint(name, ptype, api_key, base_url, model)
1146
+ choices = [""] + endpoint_choices()
1147
+ return (
1148
+ gr.update(choices=choices, value=cfg.name),
1149
+ f"βœ… Saved **{cfg.name}** ({cfg.provider} / `{cfg.model}`) β€” "
1150
+ "it's selected above. Hit **β–Ά Run Review** to use it. "
1151
+ "Tip: use πŸ”Œ Test endpoint connectivity (health tab) to check the key first.",
1152
+ _format_session_endpoints(),
1153
+ gr.update(value=""),
1154
+ gr.update(value=""),
1155
+ gr.update(value=""),
1156
+ gr.update(value=""),
1157
+ )
1158
+ except ValueError as exc:
1159
+ return (
1160
+ gr.update(),
1161
+ f"❌ {exc}",
1162
+ gr.update(),
1163
+ gr.update(),
1164
+ gr.update(),
1165
+ gr.update(),
1166
+ gr.update(),
1167
+ )
1168
+
1169
+ def on_clear_endpoints():
1170
+ """Remove all UI-added endpoints and reset the dropdown."""
1171
+ clear_session_endpoints()
1172
+ return (
1173
+ gr.update(choices=[""] + endpoint_choices(), value=""),
1174
+ "πŸ—‘ Cleared β€” dropdown reset to the built-in default.",
1175
+ _format_session_endpoints(),
1176
+ )
1177
+
1178
+ add_endpoint_btn.click(
1179
+ fn=on_add_endpoint,
1180
+ inputs=[
1181
+ ep_name_input,
1182
+ ep_type_input,
1183
+ ep_base_url_input,
1184
+ ep_api_key_input,
1185
+ ep_model_input,
1186
+ ],
1187
+ outputs=[
1188
+ endpoint_input,
1189
+ endpoint_save_msg,
1190
+ session_endpoints_display,
1191
+ ep_name_input,
1192
+ ep_base_url_input,
1193
+ ep_api_key_input,
1194
+ ep_model_input,
1195
+ ],
1196
+ )
1197
+ clear_endpoints_btn.click(
1198
+ fn=on_clear_endpoints,
1199
+ outputs=[endpoint_input, endpoint_save_msg, session_endpoints_display],
1200
+ )
1201
+
1202
  # ── Tab: Smoke Test ──────────────────────────────────────────────────
1203
  with gr.Tab("Smoke Test"):
1204
  gr.Markdown(
endpoints.py CHANGED
@@ -31,6 +31,7 @@ from __future__ import annotations
31
 
32
  import logging
33
  import os
 
34
  from dataclasses import dataclass
35
  from typing import Optional
36
 
@@ -81,7 +82,85 @@ def mask_key(api_key: str) -> str:
81
  return api_key[:6] + "…" + api_key[-4:]
82
 
83
 
84
- def discover_endpoints() -> list[EndpointConfig]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  """Scan the environment for ``OCR_ENDPOINT_<n>_*`` configs.
86
 
87
  Each index is read independently. An endpoint is registered only when
@@ -121,14 +200,33 @@ def discover_endpoints() -> list[EndpointConfig]:
121
  return endpoints
122
 
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  def get_endpoint(name: str | None) -> Optional[EndpointConfig]:
125
- """Return the first endpoint whose name matches, or ``None``."""
126
  if not name:
127
  return None
128
- for ep in discover_endpoints():
129
- if ep.name == name:
130
- return ep
131
- return None
 
132
 
133
 
134
  def endpoint_choices() -> list[str]:
 
31
 
32
  import logging
33
  import os
34
+ import threading
35
  from dataclasses import dataclass
36
  from typing import Optional
37
 
 
82
  return api_key[:6] + "…" + api_key[-4:]
83
 
84
 
85
+ # ── Runtime (UI-added) endpoints ────────────────────────────────────────────
86
+ # Endpoints entered in the web UI are kept in-memory only: they are never
87
+ # written to disk and disappear when the app process restarts. They are
88
+ # layered on top of the env-var endpoints below, so both are available and
89
+ # a UI-added endpoint with the same name as an env one takes precedence.
90
+ _session_endpoints: dict[str, EndpointConfig] = {}
91
+ # Guards the registry above β€” Gradio serves events from a thread pool, so
92
+ # concurrent visitors may register/clear endpoints at the same time.
93
+ _session_lock = threading.Lock()
94
+
95
+
96
+ def register_endpoint(
97
+ name: str,
98
+ provider: str = "openai",
99
+ api_key: str = "",
100
+ base_url: Optional[str] = None,
101
+ model: str = "",
102
+ ) -> EndpointConfig:
103
+ """Register (or replace) an endpoint added at runtime via the UI.
104
+
105
+ Validation is strict so a review never runs on a half-configured entry:
106
+
107
+ * ``name`` and ``model`` are required
108
+ * ``api_key`` is required (use a placeholder such as ``dummy`` for
109
+ keyless local servers like Ollama)
110
+ * ``provider`` must be one of :data:`SUPPORTED_PROVIDERS`
111
+
112
+ Returns the stored :class:`EndpointConfig`. Re-registering the same
113
+ name overwrites the previous entry.
114
+ """
115
+ name = (name or "").strip()
116
+ provider = (provider or "openai").strip().lower()
117
+ model = (model or "").strip()
118
+ api_key = (api_key or "").strip()
119
+ base_url = (base_url or "").strip() or None
120
+
121
+ if not name:
122
+ raise ValueError("Endpoint name is required.")
123
+ if not model:
124
+ raise ValueError("Model name is required.")
125
+ if not api_key:
126
+ raise ValueError("API key is required (use 'dummy' for keyless local servers).")
127
+ if provider not in SUPPORTED_PROVIDERS:
128
+ raise ValueError(
129
+ f"Unsupported type {provider!r} β€” use one of {SUPPORTED_PROVIDERS}."
130
+ )
131
+
132
+ cfg = EndpointConfig(
133
+ name=name,
134
+ provider=provider,
135
+ api_key=api_key,
136
+ base_url=base_url,
137
+ model=model,
138
+ )
139
+ with _session_lock:
140
+ if name in _scan_env_endpoints_by_name():
141
+ logger.warning(
142
+ "Session endpoint %r shadows an OCR_ENDPOINT_* env endpoint "
143
+ "with the same name for the rest of this process.",
144
+ name,
145
+ )
146
+ _session_endpoints[name] = cfg
147
+ logger.info("Registered session endpoint %r (%s / %s)", name, provider, model)
148
+ return cfg
149
+
150
+
151
+ def clear_session_endpoints() -> None:
152
+ """Remove every endpoint that was added at runtime via the UI."""
153
+ with _session_lock:
154
+ _session_endpoints.clear()
155
+
156
+
157
+ def session_endpoints() -> list[EndpointConfig]:
158
+ """Endpoints added at runtime via the UI (env-var ones excluded)."""
159
+ with _session_lock:
160
+ return list(_session_endpoints.values())
161
+
162
+
163
+ def _scan_env_endpoints() -> list[EndpointConfig]:
164
  """Scan the environment for ``OCR_ENDPOINT_<n>_*`` configs.
165
 
166
  Each index is read independently. An endpoint is registered only when
 
200
  return endpoints
201
 
202
 
203
+ def _scan_env_endpoints_by_name() -> dict[str, EndpointConfig]:
204
+ """Env endpoints keyed by name (helper for collision checks)."""
205
+ return {ep.name: ep for ep in _scan_env_endpoints()}
206
+
207
+
208
+ def discover_endpoints() -> list[EndpointConfig]:
209
+ """All available endpoints: env-var configs plus UI-added ones.
210
+
211
+ Endpoints added at runtime via the UI take precedence over env-var
212
+ endpoints with the same name. Entries are returned sorted by name.
213
+ """
214
+ merged: dict[str, EndpointConfig] = _scan_env_endpoints_by_name()
215
+ with _session_lock:
216
+ for ep in _session_endpoints.values():
217
+ merged[ep.name] = ep
218
+ return [merged[k] for k in sorted(merged)]
219
+
220
+
221
  def get_endpoint(name: str | None) -> Optional[EndpointConfig]:
222
+ """Return the endpoint whose name matches, or ``None``."""
223
  if not name:
224
  return None
225
+ with _session_lock:
226
+ session_ep = _session_endpoints.get(name)
227
+ if session_ep is not None:
228
+ return session_ep
229
+ return _scan_env_endpoints_by_name().get(name)
230
 
231
 
232
  def endpoint_choices() -> list[str]: