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

Deploy 798cdb73

Browse files
Files changed (4) hide show
  1. app.py +30 -19
  2. endpoints.py +77 -12
  3. llm_factory.py +27 -1
  4. main.py +3 -3
app.py CHANGED
@@ -44,7 +44,7 @@ from observability import (
44
  from endpoints import (
45
  clear_session_endpoints,
46
  discover_endpoints,
47
- endpoint_choices,
48
  register_endpoint,
49
  session_endpoints,
50
  )
@@ -521,16 +521,28 @@ def _probe_endpoint(ep) -> tuple[bool, str]:
521
 
522
 
523
  def test_endpoints() -> str:
524
- """Probe every configured endpoint and render status cards."""
 
 
 
 
 
525
  eps = discover_endpoints()
526
- if not eps:
527
- return (
528
- '<p class="muted">No custom endpoints configured β€” add '
529
- 'OCR_ENDPOINT_* secrets first.</p>'
530
- )
531
 
532
  cards = []
533
  for ep in eps:
 
 
 
 
 
 
 
 
 
 
 
 
534
  ok, detail = _probe_endpoint(ep)
535
  status_color = "#16a34a" if ok else "#dc2626"
536
  cards.append(
@@ -937,10 +949,10 @@ except Exception as exc:
937
  with gr.Blocks(title="OpenCodeReview") as demo:
938
  demo.load(js=JS_RESTORE_THEME)
939
 
940
- # Discover configured endpoints once β€” reused by the hero chip, the
941
- # dropdown, and the health accordion.
 
942
  _configured_endpoints = discover_endpoints()
943
- _endpoint_choices = [ep.name for ep in _configured_endpoints]
944
 
945
  with gr.Row():
946
  with gr.Column(scale=4):
@@ -951,8 +963,9 @@ with gr.Blocks(title="OpenCodeReview") as demo:
951
  '<h1 class="hero-title">OpenCodeReview</h1>'
952
  '<p class="hero-sub">AI-powered PR review with human-in-the-loop approval</p>'
953
  f'<div class="chips-row" style="margin-top:8px">'
954
- f'<span class="key-chip ok">⚑ {len(_configured_endpoints)} custom endpoint'
955
  f'{"s" if len(_configured_endpoints) != 1 else ""}</span>'
 
956
  '<span class="key-chip" style="color:var(--text-muted);background:var(--bg-card-alt);border-color:var(--border-color)">πŸ” BYO keys</span>'
957
  '</div>'
958
  '</div>'
@@ -984,14 +997,12 @@ with gr.Blocks(title="OpenCodeReview") as demo:
984
 
985
  with gr.Row():
986
  endpoint_input = gr.Dropdown(
987
- choices=[""] + _endpoint_choices,
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
  )
@@ -1143,7 +1154,7 @@ with gr.Blocks(title="OpenCodeReview") as demo:
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}`) β€” "
@@ -1170,7 +1181,7 @@ with gr.Blocks(title="OpenCodeReview") as demo:
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
  )
@@ -1297,7 +1308,7 @@ with gr.Blocks(title="OpenCodeReview") as demo:
1297
  gr.HTML("<ul>" + "".join(lines) + "</ul>")
1298
 
1299
  gr.HTML(
1300
- '<div class="card-title" style="margin:14px 0 8px">⚑ Custom LLM Endpoints</div>'
1301
  )
1302
  if _configured_endpoints:
1303
  endpoint_cards = "".join(
 
44
  from endpoints import (
45
  clear_session_endpoints,
46
  discover_endpoints,
47
+ dropdown_choices,
48
  register_endpoint,
49
  session_endpoints,
50
  )
 
521
 
522
 
523
  def test_endpoints() -> str:
524
+ """Probe every configured endpoint and render status cards.
525
+
526
+ Built-in providers (Gemini/Grok) whose key is not set are skipped with
527
+ a ``⏭️ key not set`` note instead of being probed (a probe would just
528
+ fail with 401 / an auth error).
529
+ """
530
  eps = discover_endpoints()
 
 
 
 
 
531
 
532
  cards = []
533
  for ep in eps:
534
+ if ep.builtin and not ep.api_key:
535
+ cards.append(
536
+ f'<div class="endpoint-card">'
537
+ f'<div class="endpoint-name">{ep.name}'
538
+ f'<span class="endpoint-badge">{ep.provider}</span></div>'
539
+ f'<div class="endpoint-meta"><code>{ep.model}</code>'
540
+ f' Β· {ep.base_url or "default URL"} Β· key {ep.masked_key}</div>'
541
+ f'<div class="endpoint-meta" style="color:var(--text-muted);font-weight:700">'
542
+ f'⏭️ key not set (add GEMINI_API_KEY / GROQ_API_KEY)</div>'
543
+ f'</div>'
544
+ )
545
+ continue
546
  ok, detail = _probe_endpoint(ep)
547
  status_color = "#16a34a" if ok else "#dc2626"
548
  cards.append(
 
949
  with gr.Blocks(title="OpenCodeReview") as demo:
950
  demo.load(js=JS_RESTORE_THEME)
951
 
952
+ # Discover configured endpoints once β€” reused by the hero chip and the
953
+ # health accordion. (The dropdown builds its grouped choices live via
954
+ # endpoints.dropdown_choices() so built-ins + added endpoints stay in sync.)
955
  _configured_endpoints = discover_endpoints()
 
956
 
957
  with gr.Row():
958
  with gr.Column(scale=4):
 
963
  '<h1 class="hero-title">OpenCodeReview</h1>'
964
  '<p class="hero-sub">AI-powered PR review with human-in-the-loop approval</p>'
965
  f'<div class="chips-row" style="margin-top:8px">'
966
+ f'<span class="key-chip ok">⚑ {len(_configured_endpoints)} endpoint'
967
  f'{"s" if len(_configured_endpoints) != 1 else ""}</span>'
968
+ '<span class="key-chip" style="color:var(--accent);background:var(--accent-soft);border-color:#6366f144">✨ Gemini · Grok built-ins</span>'
969
  '<span class="key-chip" style="color:var(--text-muted);background:var(--bg-card-alt);border-color:var(--border-color)">πŸ” BYO keys</span>'
970
  '</div>'
971
  '</div>'
 
997
 
998
  with gr.Row():
999
  endpoint_input = gr.Dropdown(
1000
+ choices=dropdown_choices(),
1001
  value="",
1002
  label="LLM Endpoint",
1003
  info=(
1004
+ "Built-in: Gemini & Grok. Pick one, or add your own below. "
1005
+ "Empty = auto (Gemini β†’ Grok fallback)."
 
 
1006
  ),
1007
  scale=3,
1008
  )
 
1154
  """Register the form values, refresh the dropdown, auto-select."""
1155
  try:
1156
  cfg = register_endpoint(name, ptype, api_key, base_url, model)
1157
+ choices = dropdown_choices()
1158
  return (
1159
  gr.update(choices=choices, value=cfg.name),
1160
  f"βœ… Saved **{cfg.name}** ({cfg.provider} / `{cfg.model}`) β€” "
 
1181
  """Remove all UI-added endpoints and reset the dropdown."""
1182
  clear_session_endpoints()
1183
  return (
1184
+ gr.update(choices=dropdown_choices(), value=""),
1185
  "πŸ—‘ Cleared β€” dropdown reset to the built-in default.",
1186
  _format_session_endpoints(),
1187
  )
 
1308
  gr.HTML("<ul>" + "".join(lines) + "</ul>")
1309
 
1310
  gr.HTML(
1311
+ '<div class="card-title" style="margin:14px 0 8px">⚑ LLM Endpoints</div>'
1312
  )
1313
  if _configured_endpoints:
1314
  endpoint_cards = "".join(
endpoints.py CHANGED
@@ -52,6 +52,7 @@ class EndpointConfig:
52
  base_url: Optional[str] = None
53
  model: str = ""
54
  index: int = 0 # the env-var index the endpoint came from
 
55
 
56
  def __post_init__(self) -> None:
57
  self.provider = (self.provider or "openai").strip().lower()
@@ -137,10 +138,13 @@ def register_endpoint(
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
@@ -205,13 +209,45 @@ def _scan_env_endpoints_by_name() -> dict[str, EndpointConfig]:
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
@@ -219,16 +255,45 @@ def discover_endpoints() -> list[EndpointConfig]:
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]:
233
- """Names of all configured endpoints, for the UI dropdown."""
234
- return [ep.name for ep in discover_endpoints()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  base_url: Optional[str] = None
53
  model: str = ""
54
  index: int = 0 # the env-var index the endpoint came from
55
+ builtin: bool = False # True for the always-available Gemini/Grok providers
56
 
57
  def __post_init__(self) -> None:
58
  self.provider = (self.provider or "openai").strip().lower()
 
138
  model=model,
139
  )
140
  with _session_lock:
141
+ if name in _scan_env_endpoints_by_name() or any(
142
+ ep.name == name for ep in builtin_endpoints()
143
+ ):
144
  logger.warning(
145
+ "Session endpoint %r shadows an existing endpoint "
146
+ "(OCR_ENDPOINT_* env or built-in) with the same name for "
147
+ "the rest of this process.",
148
  name,
149
  )
150
  _session_endpoints[name] = cfg
 
209
  return {ep.name: ep for ep in _scan_env_endpoints()}
210
 
211
 
212
+ def builtin_endpoints() -> list[EndpointConfig]:
213
+ """The always-available built-in providers (Gemini, Grok).
214
+
215
+ These are surfaced as selectable endpoints so the UI/CLI can choose
216
+ explicitly between them. They read their keys from the standard
217
+ ``GEMINI_API_KEY`` / ``GROQ_API_KEY`` env vars and run on the same
218
+ models as the default (no-endpoint) path.
219
+ """
220
+ from llm_factory import GEMINI_MODEL, GROQ_MODEL
221
+
222
+ return [
223
+ EndpointConfig(
224
+ name="Gemini",
225
+ provider="google",
226
+ api_key=os.environ.get("GEMINI_API_KEY", "").strip(),
227
+ model=GEMINI_MODEL,
228
+ builtin=True,
229
+ ),
230
+ EndpointConfig(
231
+ name="Grok",
232
+ provider="openai",
233
+ api_key=os.environ.get("GROQ_API_KEY", "").strip(),
234
+ base_url="https://api.groq.com/openai/v1",
235
+ model=GROQ_MODEL,
236
+ builtin=True,
237
+ ),
238
+ ]
239
+
240
+
241
  def discover_endpoints() -> list[EndpointConfig]:
242
+ """All available endpoints: built-ins + env-var configs + UI-added ones.
243
 
244
+ Precedence on name collision: UI-added (session) > env-var > built-in.
245
+ Entries are returned sorted by name.
246
  """
247
+ merged: dict[str, EndpointConfig] = {
248
+ ep.name: ep for ep in builtin_endpoints()
249
+ }
250
+ merged.update(_scan_env_endpoints_by_name())
251
  with _session_lock:
252
  for ep in _session_endpoints.values():
253
  merged[ep.name] = ep
 
255
 
256
 
257
  def get_endpoint(name: str | None) -> Optional[EndpointConfig]:
258
+ """Return the endpoint whose name matches, or ``None``.
259
+
260
+ Resolution order: UI-added (session) β†’ env-var β†’ built-in.
261
+ """
262
  if not name:
263
  return None
264
  with _session_lock:
265
  session_ep = _session_endpoints.get(name)
266
  if session_ep is not None:
267
  return session_ep
268
+ env_ep = _scan_env_endpoints_by_name().get(name)
269
+ if env_ep is not None:
270
+ return env_ep
271
+ return next((b for b in builtin_endpoints() if b.name == name), None)
272
+
273
 
274
+ def dropdown_choices() -> list[str | tuple[str, list[str]]]:
275
+ """Grouped choices for the UI dropdown.
276
 
277
+ Returns a Gradio-compatible choice list with two optgroups:
278
+ ``("Built-in", ["Gemini", "Grok"])`` and ``("Custom", [...])`` β€”
279
+ so the user can pick a *section* for the built-in providers vs the
280
+ custom endpoints they configured. An empty string entry keeps the
281
+ "auto" (no-endpoint) option first.
282
+
283
+ A built-in is omitted from its group when a custom endpoint shadows it
284
+ by name (session > env > built-in precedence), so each name appears
285
+ exactly once.
286
+ """
287
+ custom_names = [
288
+ ep.name for ep in discover_endpoints() if not ep.builtin
289
+ ]
290
+ builtin_names = [
291
+ ep.name for ep in builtin_endpoints()
292
+ if ep.name not in custom_names
293
+ ]
294
+ choices: list = [""]
295
+ if builtin_names:
296
+ choices.append(("Built-in", builtin_names))
297
+ if custom_names:
298
+ choices.append(("Custom", custom_names))
299
+ return choices
llm_factory.py CHANGED
@@ -195,6 +195,31 @@ def create_llm(endpoint=None, **kwargs: Any) -> Any:
195
 
196
  ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
197
  if ep is not None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  try:
199
  llm = create_endpoint_llm(ep, **kwargs)
200
  logger.info("Using custom endpoint %s (%s/%s)", ep.name, ep.provider, ep.model)
@@ -204,7 +229,8 @@ def create_llm(endpoint=None, **kwargs: Any) -> Any:
204
  else:
205
  raise ValueError(
206
  f"Custom endpoint '{endpoint}' not found. "
207
- "Configure it via OCR_ENDPOINT_* environment variables."
 
208
  )
209
 
210
  llm = _get_gemini_chat(**kwargs)
 
195
 
196
  ep = endpoint if isinstance(endpoint, EndpointConfig) else get_endpoint(endpoint)
197
  if ep is not None:
198
+ if getattr(ep, "builtin", False):
199
+ # Built-in providers use their native constructors so the
200
+ # behaviour is identical to the default (no-endpoint) path.
201
+ if ep.name == "Gemini":
202
+ llm = _get_gemini_chat(**kwargs)
203
+ if llm is not None:
204
+ logger.info(
205
+ "Using built-in Gemini endpoint (model=%s)",
206
+ kwargs.get("model", GEMINI_MODEL),
207
+ )
208
+ return llm
209
+ raise ValueError(
210
+ "Gemini selected but GEMINI_API_KEY is not set."
211
+ )
212
+ if ep.name == "Grok":
213
+ llm = _get_groq_chat(**kwargs)
214
+ if llm is not None:
215
+ logger.info(
216
+ "Using built-in Grok endpoint (model=%s)",
217
+ kwargs.get("model", GROQ_MODEL),
218
+ )
219
+ return llm
220
+ raise ValueError(
221
+ "Grok selected but GROQ_API_KEY is not set."
222
+ )
223
  try:
224
  llm = create_endpoint_llm(ep, **kwargs)
225
  logger.info("Using custom endpoint %s (%s/%s)", ep.name, ep.provider, ep.model)
 
229
  else:
230
  raise ValueError(
231
  f"Custom endpoint '{endpoint}' not found. "
232
+ "Configure it via OCR_ENDPOINT_* environment variables "
233
+ "or add it in the UI."
234
  )
235
 
236
  llm = _get_gemini_chat(**kwargs)
main.py CHANGED
@@ -180,7 +180,7 @@ SYNTHETIC_STATE = {
180
  "--endpoint", "endpoint_name",
181
  default="",
182
  show_default=True,
183
- help="Name of a configured custom LLM endpoint (see OCR_ENDPOINT_* env vars).",
184
  )
185
  def review(repo: str, pr_number: int, smoke: bool, endpoint_name: str) -> None:
186
  """Run a PR review with human-in-the-loop approval.
@@ -540,8 +540,8 @@ def doctor() -> None:
540
  click.echo(f" {comp}: {status}")
541
  click.echo()
542
 
543
- # ── Custom endpoints ────────────────────────────────────────────────
544
- click.echo("πŸ”Œ Custom Endpoints")
545
  from endpoints import discover_endpoints
546
 
547
  eps = discover_endpoints()
 
180
  "--endpoint", "endpoint_name",
181
  default="",
182
  show_default=True,
183
+ help="LLM endpoint: Gemini/Grok (built-ins) or a custom name (see OCR_ENDPOINT_* env vars).",
184
  )
185
  def review(repo: str, pr_number: int, smoke: bool, endpoint_name: str) -> None:
186
  """Run a PR review with human-in-the-loop approval.
 
540
  click.echo(f" {comp}: {status}")
541
  click.echo()
542
 
543
+ # ── LLM endpoints (built-ins + custom) ───────────────────────────────
544
+ click.echo("πŸ”Œ LLM Endpoints")
545
  from endpoints import discover_endpoints
546
 
547
  eps = discover_endpoints()