DhyandevP commited on
Commit
2d7da08
·
1 Parent(s): 38439be

fix(routing): auto-route new Google AI Studio AQ. keys and Gemini models to Google endpoint

Browse files
Files changed (5) hide show
  1. README.md +9 -9
  2. index.html +11 -13
  3. main.py +22 -11
  4. test_app.py +26 -0
  5. tester.html +8 -27
README.md CHANGED
@@ -25,12 +25,13 @@ To prevent unauthorized public access and ensure only your applications can send
25
  - Acts as your **Model Control Panel**.
26
  - Select and save which model the evaluator should use (e.g. `gemini-2.0-flash`, `gpt-4o-mini`, `llama-3.3-70b-versatile`, or custom).
27
  2. **External Evaluation Endpoint (`POST /evaluate`)**:
28
- - External applications send:
 
 
29
  - Header: `X-API-Key: YOUR_SERVICE_ACCESS_KEY`
 
30
  - `question`: The problem statement or objective.
31
  - `code` (or `file`): Code text or `.zip`/source file.
32
- - `api_key`: Your AI provider API key (Google Gemini, OpenAI, Groq, DeepSeek, etc.).
33
- - `base_url`: Your provider's OpenAI-compatible base URL.
34
  - The server evaluates the code using the currently active model and returns:
35
  ```json
36
  {
@@ -46,14 +47,15 @@ To prevent unauthorized public access and ensure only your applications can send
46
  ```python
47
  import requests
48
 
 
49
  url = "https://dhyandevp-codeevaluator.hf.space/evaluate"
 
 
50
  headers = {"X-API-Key": "YOUR_SERVICE_ACCESS_KEY"}
51
 
52
  payload = {
53
  "question": "Write a function to check if a string is a palindrome.",
54
- "code": "def is_palindrome(s): return s == s[::-1]",
55
- "api_key": "YOUR_LLM_KEY",
56
- "base_url": "https://generativelanguage.googleapis.com/v1beta/openai/" # or https://api.openai.com/v1
57
  }
58
 
59
  res = requests.post(url, headers=headers, json=payload).json()
@@ -68,8 +70,6 @@ curl -X POST "https://dhyandevp-codeevaluator.hf.space/evaluate" \
68
  -H "X-API-Key: YOUR_SERVICE_ACCESS_KEY" \
69
  -d '{
70
  "question": "Write a function to reverse a list in Python.",
71
- "code": "def reverse_list(arr): return arr[::-1]",
72
- "api_key": "YOUR_LLM_KEY",
73
- "base_url": "https://generativelanguage.googleapis.com/v1beta/openai/"
74
  }'
75
  ```
 
25
  - Acts as your **Model Control Panel**.
26
  - Select and save which model the evaluator should use (e.g. `gemini-2.0-flash`, `gpt-4o-mini`, `llama-3.3-70b-versatile`, or custom).
27
  2. **External Evaluation Endpoint (`POST /evaluate`)**:
28
+ - The AI provider key and provider base URL are securely locked in Hugging Face Secrets (`OPENAI_API_KEY`, `OPENAI_BASE_URL`).
29
+ - The model is locked to the Hugging Face Web UI model switch.
30
+ - External client applications only provide:
31
  - Header: `X-API-Key: YOUR_SERVICE_ACCESS_KEY`
32
+ - Service Base URL: `https://<your-space>.hf.space/evaluate`
33
  - `question`: The problem statement or objective.
34
  - `code` (or `file`): Code text or `.zip`/source file.
 
 
35
  - The server evaluates the code using the currently active model and returns:
36
  ```json
37
  {
 
47
  ```python
48
  import requests
49
 
50
+ # Base URL of your Hugging Face Space:
51
  url = "https://dhyandevp-codeevaluator.hf.space/evaluate"
52
+
53
+ # Service API Key configured in your HF Space Secrets:
54
  headers = {"X-API-Key": "YOUR_SERVICE_ACCESS_KEY"}
55
 
56
  payload = {
57
  "question": "Write a function to check if a string is a palindrome.",
58
+ "code": "def is_palindrome(s): return s == s[::-1]"
 
 
59
  }
60
 
61
  res = requests.post(url, headers=headers, json=payload).json()
 
70
  -H "X-API-Key: YOUR_SERVICE_ACCESS_KEY" \
71
  -d '{
72
  "question": "Write a function to reverse a list in Python.",
73
+ "code": "def reverse_list(arr): return arr[::-1]"
 
 
74
  }'
75
  ```
index.html CHANGED
@@ -206,7 +206,7 @@
206
  <div class="card">
207
  <div class="section-title">🚀 Send Requests from External API</div>
208
  <p style="font-size: 0.88rem; color: var(--text-muted); line-height: 1.5;">
209
- Send questions and code from your external application directly to <code>POST /evaluate</code> along with your <code>api_key</code> and <code>base_url</code>. The server grades the code using the active model selected above and returns the score and feedback directly to your application.
210
  </p>
211
 
212
  <div class="tabs">
@@ -217,16 +217,15 @@
217
 
218
  <pre class="code-block" id="snippetPython"><code>import requests
219
 
 
220
  url = "https://dhyandevp-codeevaluator.hf.space/evaluate"
221
 
222
- # If you protected your Space with SERVICE_API_KEY in HF Secrets, pass it in headers:
223
  headers = {"X-API-Key": "YOUR_SERVICE_ACCESS_KEY"}
224
 
225
  payload = {
226
  "question": "Write a function that calculates factorial of n.",
227
- "code": "def factorial(n):\n return 1 if n <= 1 else n * factorial(n - 1)",
228
- "api_key": "YOUR_LLM_API_KEY", # e.g. AIzaSy... or sk-...
229
- "base_url": "https://generativelanguage.googleapis.com/v1beta/openai/" # or https://api.openai.com/v1
230
  }
231
 
232
  res = requests.post(url, headers=headers, json=payload).json()
@@ -238,12 +237,12 @@ print("Feedback:", res["feedback"])</code></pre>
238
  -H "X-API-Key: YOUR_SERVICE_ACCESS_KEY" \
239
  -d '{
240
  "question": "Write a function that calculates factorial of n.",
241
- "code": "def factorial(n): return 1 if n <= 1 else n * factorial(n - 1)",
242
- "api_key": "YOUR_LLM_API_KEY",
243
- "base_url": "https://generativelanguage.googleapis.com/v1beta/openai/"
244
  }'</code></pre>
245
 
246
- <pre class="code-block" id="snippetJs" style="display: none;"><code>const res = await fetch("https://dhyandevp-codeevaluator.hf.space/evaluate", {
 
 
247
  method: "POST",
248
  headers: {
249
  "Content-Type": "application/json",
@@ -251,14 +250,13 @@ print("Feedback:", res["feedback"])</code></pre>
251
  },
252
  body: JSON.stringify({
253
  question: "Write a function that calculates factorial of n.",
254
- code: "function factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); }",
255
- api_key: "YOUR_LLM_API_KEY",
256
- base_url: "https://generativelanguage.googleapis.com/v1beta/openai/"
257
  })
258
  });
259
 
260
  const data = await res.json();
261
- console.log(data.score, data.feedback);</code></pre>
 
262
  </div>
263
  </div>
264
 
 
206
  <div class="card">
207
  <div class="section-title">🚀 Send Requests from External API</div>
208
  <p style="font-size: 0.88rem; color: var(--text-muted); line-height: 1.5;">
209
+ The AI Provider credentials are secured in Hugging Face Secrets (<code>OPENAI_API_KEY</code> / <code>OPENAI_BASE_URL</code>) and the active model is managed via the selector above. External clients only need to specify the <strong>Service Base URL</strong>, provide their <strong>Service API Key</strong> (<code>X-API-Key</code>), and send the <strong>code submission</strong>.
210
  </p>
211
 
212
  <div class="tabs">
 
217
 
218
  <pre class="code-block" id="snippetPython"><code>import requests
219
 
220
+ # Service Base URL of your Hugging Face Space:
221
  url = "https://dhyandevp-codeevaluator.hf.space/evaluate"
222
 
223
+ # Service Access Key configured in your HF Space Secrets:
224
  headers = {"X-API-Key": "YOUR_SERVICE_ACCESS_KEY"}
225
 
226
  payload = {
227
  "question": "Write a function that calculates factorial of n.",
228
+ "code": "def factorial(n):\n return 1 if n <= 1 else n * factorial(n - 1)"
 
 
229
  }
230
 
231
  res = requests.post(url, headers=headers, json=payload).json()
 
237
  -H "X-API-Key: YOUR_SERVICE_ACCESS_KEY" \
238
  -d '{
239
  "question": "Write a function that calculates factorial of n.",
240
+ "code": "def factorial(n): return 1 if n <= 1 else n * factorial(n - 1)"
 
 
241
  }'</code></pre>
242
 
243
+ <pre class="code-block" id="snippetJs" style="display: none;"><code>const url = "https://dhyandevp-codeevaluator.hf.space/evaluate";
244
+
245
+ const res = await fetch(url, {
246
  method: "POST",
247
  headers: {
248
  "Content-Type": "application/json",
 
250
  },
251
  body: JSON.stringify({
252
  question: "Write a function that calculates factorial of n.",
253
+ code: "function factorial(n) { return n <= 1 ? 1 : n * factorial(n - 1); }"
 
 
254
  })
255
  });
256
 
257
  const data = await res.json();
258
+ console.log("Score:", data.score);
259
+ console.log("Feedback:", data.feedback);</code></pre>
260
  </div>
261
  </div>
262
 
main.py CHANGED
@@ -7,7 +7,7 @@ import zipfile
7
  from fastapi import FastAPI, HTTPException, Request
8
  from fastapi.middleware.cors import CORSMiddleware
9
  from fastapi.responses import FileResponse, JSONResponse
10
- from openai import AsyncOpenAI
11
  from pydantic import BaseModel
12
 
13
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")
@@ -204,22 +204,23 @@ async def evaluate_code(request: Request) -> dict:
204
  if not code_text:
205
  raise HTTPException(status_code=400, detail="Missing 'code' or 'file' in request.")
206
 
207
- # Resolve credentials from external request, with environment secret fallback
208
- active_key = api_key or os.getenv("OPENAI_API_KEY", "").strip() or os.getenv("GEMINI_API_KEY", "").strip()
209
- active_base_url = base_url or os.getenv("OPENAI_BASE_URL", "").strip()
210
- active_model = model_override or get_active_model()
211
 
212
  if not active_key:
213
  raise HTTPException(
214
  status_code=400,
215
- detail="Missing AI API key. Please configure OPENAI_API_KEY in Hugging Face Secrets or include 'api_key' in the request.",
216
  )
217
 
218
- # Auto-route Google Gemini keys if base_url wasn't specified
219
- if active_key.startswith("AIza") and not active_base_url:
220
- active_base_url = "https://generativelanguage.googleapis.com/v1beta/openai/"
221
- elif not active_base_url:
222
- active_base_url = "https://api.openai.com/v1"
 
223
 
224
  client = AsyncOpenAI(api_key=active_key, base_url=active_base_url)
225
  user_prompt = f"<QUESTION_OBJECTIVE>\n{question}\n</QUESTION_OBJECTIVE>\n\n<CODE_SUBMISSION>\n{code_text}\n</CODE_SUBMISSION>"
@@ -241,6 +242,16 @@ async def evaluate_code(request: Request) -> dict:
241
  "feedback": str(result.get("feedback", "No feedback provided.")).strip(),
242
  "model": active_model,
243
  }
 
 
 
 
 
 
 
 
 
 
244
  except json.JSONDecodeError:
245
  logger.exception("Could not parse LLM JSON response.")
246
  raise HTTPException(status_code=502, detail="LLM returned an invalid JSON response.")
 
7
  from fastapi import FastAPI, HTTPException, Request
8
  from fastapi.middleware.cors import CORSMiddleware
9
  from fastapi.responses import FileResponse, JSONResponse
10
+ from openai import APIError, AsyncOpenAI, AuthenticationError
11
  from pydantic import BaseModel
12
 
13
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")
 
204
  if not code_text:
205
  raise HTTPException(status_code=400, detail="Missing 'code' or 'file' in request.")
206
 
207
+ # Resolve credentials: HF Secrets are primary; model is strictly locked to HF model selector
208
+ active_key = os.getenv("OPENAI_API_KEY", "").strip() or os.getenv("GEMINI_API_KEY", "").strip() or api_key
209
+ active_base_url = os.getenv("OPENAI_BASE_URL", "").strip() or base_url
210
+ active_model = get_active_model()
211
 
212
  if not active_key:
213
  raise HTTPException(
214
  status_code=400,
215
+ detail="Missing AI provider key. Please configure OPENAI_API_KEY in your Hugging Face Space Secrets.",
216
  )
217
 
218
+ # Auto-route base_url if not explicitly provided
219
+ if not active_base_url:
220
+ if active_key.startswith(("AIza", "AQ.")) or active_model.lower().startswith("gemini"):
221
+ active_base_url = "https://generativelanguage.googleapis.com/v1beta/openai/"
222
+ else:
223
+ active_base_url = "https://api.openai.com/v1"
224
 
225
  client = AsyncOpenAI(api_key=active_key, base_url=active_base_url)
226
  user_prompt = f"<QUESTION_OBJECTIVE>\n{question}\n</QUESTION_OBJECTIVE>\n\n<CODE_SUBMISSION>\n{code_text}\n</CODE_SUBMISSION>"
 
242
  "feedback": str(result.get("feedback", "No feedback provided.")).strip(),
243
  "model": active_model,
244
  }
245
+ except AuthenticationError as exc:
246
+ logger.error("Authentication failed with provider at %s: %s", active_base_url, exc)
247
+ raise HTTPException(
248
+ status_code=401,
249
+ detail=f"AI Provider authentication failed at {active_base_url}. Please verify your API key.",
250
+ )
251
+ except APIError as exc:
252
+ logger.error("Provider API error at %s: %s", active_base_url, exc)
253
+ status = exc.status_code if getattr(exc, "status_code", None) else 502
254
+ raise HTTPException(status_code=status, detail=f"AI Provider error: {exc.message}")
255
  except json.JSONDecodeError:
256
  logger.exception("Could not parse LLM JSON response.")
257
  raise HTTPException(status_code=502, detail="LLM returned an invalid JSON response.")
test_app.py CHANGED
@@ -108,6 +108,31 @@ def test_evaluate_mocked_form():
108
  assert data["score"] == 85
109
 
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  def test_service_key_authorization():
112
  import os
113
  client = TestClient(app)
@@ -152,5 +177,6 @@ if __name__ == "__main__":
152
  test_evaluate_validation()
153
  test_evaluate_mocked_json()
154
  test_evaluate_mocked_form()
 
155
  test_service_key_authorization()
156
  print("All unit tests passed successfully!")
 
108
  assert data["score"] == 85
109
 
110
 
111
+ def test_gemini_key_autorouting():
112
+ client = TestClient(app)
113
+ mock_resp = MagicMock()
114
+ mock_choice = MagicMock()
115
+ mock_choice.message.content = '{"score": 95, "feedback": "Excellent."}'
116
+ mock_resp.choices = [mock_choice]
117
+
118
+ with patch("main.AsyncOpenAI") as mock_openai_cls:
119
+ mock_instance = MagicMock()
120
+ mock_openai_cls.return_value = mock_instance
121
+ mock_instance.chat.completions.create = AsyncMock(return_value=mock_resp)
122
+
123
+ # Keys starting with AQ. should auto-route to Google Gemini base_url
124
+ res = client.post("/evaluate", json={
125
+ "question": "Reverse string",
126
+ "code": "def rev(s): return s[::-1]",
127
+ "api_key": "AQ.Ab8RN_Test_Key"
128
+ })
129
+ assert res.status_code == 200
130
+ mock_openai_cls.assert_called_with(
131
+ api_key="AQ.Ab8RN_Test_Key",
132
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
133
+ )
134
+
135
+
136
  def test_service_key_authorization():
137
  import os
138
  client = TestClient(app)
 
177
  test_evaluate_validation()
178
  test_evaluate_mocked_json()
179
  test_evaluate_mocked_form()
180
+ test_gemini_key_autorouting()
181
  test_service_key_authorization()
182
  print("All unit tests passed successfully!")
tester.html CHANGED
@@ -276,7 +276,7 @@
276
  <header>
277
  <div class="header-titles">
278
  <h1>Code Evaluator Tester</h1>
279
- <p>Test the <code>/evaluate</code> endpoint with your custom API keys</p>
280
  </div>
281
  <div>
282
  <a href="https://dhyandevp-codeevaluator.hf.space" target="_blank" class="nav-link">Model Control Panel &rarr;</a>
@@ -289,34 +289,21 @@
289
  <!-- API Configuration Card -->
290
  <div class="card">
291
  <div class="card-title">
292
- <span>1. Endpoint & Access Credentials</span>
 
293
  </div>
294
 
295
  <div class="form-row">
296
  <div class="form-group">
297
- <label for="endpointUrl">Evaluator URL</label>
298
  <input type="text" id="endpointUrl" value="https://dhyandevp-codeevaluator.hf.space/evaluate" />
299
- <span class="help-hint">Or use <code>http://localhost:7860/evaluate</code> if running locally.</span>
300
  </div>
301
 
302
  <div class="form-group">
303
- <label for="serviceKey">Service Access Key (<code>X-API-Key</code>)</label>
304
  <input type="password" id="serviceKey" placeholder="Matches your SERVICE_API_KEY HF Secret" />
305
- <span class="help-hint">Leave blank only if your Space has no SERVICE_API_KEY set.</span>
306
- </div>
307
- </div>
308
-
309
- <div class="form-row">
310
- <div class="form-group">
311
- <label for="providerKey">AI Provider Key (Optional)</label>
312
- <input type="password" id="providerKey" placeholder="Gemini or OpenAI API key (optional)" />
313
- <span class="help-hint">Optional if <code>OPENAI_API_KEY</code> is already configured in HF Secrets.</span>
314
- </div>
315
-
316
- <div class="form-group">
317
- <label for="baseUrl">Provider Base URL (Optional)</label>
318
- <input type="text" id="baseUrl" placeholder="https://generativelanguage.googleapis.com/v1beta/openai/" />
319
- <span class="help-hint">Optional if <code>OPENAI_BASE_URL</code> is set in HF Secrets.</span>
320
  </div>
321
  </div>
322
  </div>
@@ -458,13 +445,11 @@
458
  hideError();
459
  const endpoint = document.getElementById('endpointUrl').value.trim();
460
  const serviceKey = document.getElementById('serviceKey').value.trim();
461
- const providerKey = document.getElementById('providerKey').value.trim();
462
- const baseUrl = document.getElementById('baseUrl').value.trim();
463
  const question = document.getElementById('questionInput').value.trim();
464
  const code = document.getElementById('codeInput').value.trim();
465
 
466
  if (!endpoint) {
467
- showError("Please specify the Evaluator endpoint URL.");
468
  return;
469
  }
470
  if (!question) {
@@ -502,8 +487,6 @@
502
  if (currentMode === 'text') {
503
  headers['Content-Type'] = 'application/json';
504
  const payload = { question, code };
505
- if (providerKey) payload.api_key = providerKey;
506
- if (baseUrl) payload.base_url = baseUrl;
507
 
508
  response = await fetch(endpoint, {
509
  method: 'POST',
@@ -514,8 +497,6 @@
514
  const formData = new FormData();
515
  formData.append('question', question);
516
  formData.append('file', selectedFile);
517
- if (providerKey) formData.append('api_key', providerKey);
518
- if (baseUrl) formData.append('base_url', baseUrl);
519
 
520
  response = await fetch(endpoint, {
521
  method: 'POST',
 
276
  <header>
277
  <div class="header-titles">
278
  <h1>Code Evaluator Tester</h1>
279
+ <p>Test the <code>/evaluate</code> endpoint with your service credentials</p>
280
  </div>
281
  <div>
282
  <a href="https://dhyandevp-codeevaluator.hf.space" target="_blank" class="nav-link">Model Control Panel &rarr;</a>
 
289
  <!-- API Configuration Card -->
290
  <div class="card">
291
  <div class="card-title">
292
+ <span>1. Service Connection & Access</span>
293
+ <span style="font-size: 0.8rem; font-weight: 500; color: #3fb950; background: rgba(63, 185, 80, 0.1); border: 1px solid rgba(63, 185, 80, 0.3); padding: 3px 8px; border-radius: 6px;">🔒 AI Key & Model managed in Hugging Face</span>
294
  </div>
295
 
296
  <div class="form-row">
297
  <div class="form-group">
298
+ <label for="endpointUrl">Service Base URL / Endpoint</label>
299
  <input type="text" id="endpointUrl" value="https://dhyandevp-codeevaluator.hf.space/evaluate" />
300
+ <span class="help-hint">Your Hugging Face Space endpoint (or <code>http://localhost:7860/evaluate</code> if local).</span>
301
  </div>
302
 
303
  <div class="form-group">
304
+ <label for="serviceKey">Service API Key (<code>X-API-Key</code>)</label>
305
  <input type="password" id="serviceKey" placeholder="Matches your SERVICE_API_KEY HF Secret" />
306
+ <span class="help-hint">Leave blank only if your Space has no SERVICE_API_KEY secret configured.</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
  </div>
308
  </div>
309
  </div>
 
445
  hideError();
446
  const endpoint = document.getElementById('endpointUrl').value.trim();
447
  const serviceKey = document.getElementById('serviceKey').value.trim();
 
 
448
  const question = document.getElementById('questionInput').value.trim();
449
  const code = document.getElementById('codeInput').value.trim();
450
 
451
  if (!endpoint) {
452
+ showError("Please specify the Service Base URL / Endpoint.");
453
  return;
454
  }
455
  if (!question) {
 
487
  if (currentMode === 'text') {
488
  headers['Content-Type'] = 'application/json';
489
  const payload = { question, code };
 
 
490
 
491
  response = await fetch(endpoint, {
492
  method: 'POST',
 
497
  const formData = new FormData();
498
  formData.append('question', question);
499
  formData.append('file', selectedFile);
 
 
500
 
501
  response = await fetch(endpoint, {
502
  method: 'POST',