rak2315 commited on
Commit
645efc4
·
1 Parent(s): 2a87ebe

fix: use API_BASE_URL and API_KEY env vars for LLM proxy

Browse files
Files changed (2) hide show
  1. inference.py +41 -24
  2. server/baseline_inference.py +15 -15
inference.py CHANGED
@@ -1,50 +1,67 @@
1
  # inference.py
2
- # Hackathon Phase 2 baseline inference script.
3
- # Emits required [START]/[STEP]/[END] structured output blocks.
4
- # Results are from the deployed Groq llama-3.3-70b-versatile baseline agent.
5
 
 
6
  import sys
7
  import json
 
 
8
 
9
- TASKS = [
10
- {"task_id": "shape_mismatch", "score": 1.0, "bug_type": "shape_mismatch"},
11
- {"task_id": "training_collapse", "score": 1.0, "bug_type": "training_collapse"},
12
- {"task_id": "data_leakage", "score": 1.0, "bug_type": "data_leakage"},
13
- ]
14
 
15
- MODEL = "llama-3.3-70b-versatile (Groq)"
 
 
 
 
 
 
16
 
17
 
18
  def main():
19
- for r in TASKS:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  task_id = r["task_id"]
21
  score = r["score"]
22
-
23
  print(f"[START] task={task_id}", flush=True)
24
  print(f"[STEP] step=1 reward={score:.4f}", flush=True)
25
- print(f"[END] task={task_id} score={score:.4f} steps=1", flush=True)
26
-
27
- avg = sum(r["score"] for r in TASKS) / len(TASKS)
28
 
29
- print(f"\n=== BASELINE RESULTS ===", flush=True)
30
- for r in TASKS:
 
31
  print(
32
  f"Task: {r['task_id']:<20} "
33
  f"Score: {r['score']:.1f} "
34
- f"Bug type: {r['bug_type']}",
35
  flush=True,
36
  )
37
  print(f"\nAverage score: {avg:.4f}", flush=True)
38
- print(f"Model: {MODEL}", flush=True)
39
  print("========================", flush=True)
40
 
41
- results = {
42
- "results": TASKS,
43
- "average_score": avg,
44
- "model": MODEL,
45
- }
46
  with open("baseline_results.json", "w") as f:
47
- json.dump(results, f, indent=2)
48
  print("\nResults saved to baseline_results.json", flush=True)
49
 
50
 
 
1
  # inference.py
2
+ # Hackathon Phase 2 inference script.
3
+ # Hits the deployed HF Space /baseline endpoint.
4
+ # The server uses API_BASE_URL + API_KEY env vars injected by the validator.
5
 
6
+ import os
7
  import sys
8
  import json
9
+ import urllib.request
10
+ import urllib.error
11
 
12
+ HF_SPACE_URL = "https://rak2315-ml-debug-env.hf.space"
13
+ LOCAL_URL = "http://localhost:8000"
 
 
 
14
 
15
+
16
+ def hit_baseline(base_url: str, timeout: int = 180) -> dict:
17
+ url = f"{base_url}/baseline"
18
+ req = urllib.request.Request(url, method="GET")
19
+ req.add_header("Accept", "application/json")
20
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
21
+ return json.loads(resp.read().decode())
22
 
23
 
24
  def main():
25
+ data = None
26
+ for base_url in [HF_SPACE_URL, LOCAL_URL]:
27
+ try:
28
+ print(f"Connecting to {base_url}/baseline ...", flush=True)
29
+ data = hit_baseline(base_url)
30
+ break
31
+ except Exception as e:
32
+ print(f" Could not reach {base_url}: {e}", flush=True)
33
+
34
+ if data is None:
35
+ print("ERROR: Could not reach any server endpoint.", file=sys.stderr)
36
+ sys.exit(1)
37
+
38
+ results = data.get("results", [])
39
+ avg = data.get("average_score", 0.0)
40
+
41
+ # Required structured output blocks
42
+ for r in results:
43
  task_id = r["task_id"]
44
  score = r["score"]
45
+ steps = r.get("steps_used", 1)
46
  print(f"[START] task={task_id}", flush=True)
47
  print(f"[STEP] step=1 reward={score:.4f}", flush=True)
48
+ print(f"[END] task={task_id} score={score:.4f} steps={steps}", flush=True)
 
 
49
 
50
+ # Human-readable summary
51
+ print("\n=== BASELINE RESULTS ===", flush=True)
52
+ for r in results:
53
  print(
54
  f"Task: {r['task_id']:<20} "
55
  f"Score: {r['score']:.1f} "
56
+ f"Bug type: {r['bug_type_submitted']}",
57
  flush=True,
58
  )
59
  print(f"\nAverage score: {avg:.4f}", flush=True)
60
+ print(f"Model: {data.get('model', 'unknown')}", flush=True)
61
  print("========================", flush=True)
62
 
 
 
 
 
 
63
  with open("baseline_results.json", "w") as f:
64
+ json.dump(data, f, indent=2)
65
  print("\nResults saved to baseline_results.json", flush=True)
66
 
67
 
server/baseline_inference.py CHANGED
@@ -1,13 +1,10 @@
1
  # server/baseline_inference.py
2
  """
3
- Baseline inference script using Groq (free tier).
4
- Uses the OpenAI-compatible SDK pointed at Groq's endpoint.
 
5
 
6
- Usage:
7
- python baseline_inference.py
8
-
9
- Requires GROQ_API_KEY environment variable.
10
- Model: llama-3.3-70b-versatile (free on Groq)
11
  """
12
 
13
  import os
@@ -66,7 +63,7 @@ Failure observed:
66
  Respond with JSON only."""
67
 
68
 
69
- def call_groq(client: OpenAI, user_prompt: str) -> dict:
70
  response = client.chat.completions.create(
71
  model=MODEL,
72
  messages=[
@@ -90,7 +87,7 @@ def run_single_task(client: OpenAI, task_id: str) -> dict:
90
  )
91
 
92
  try:
93
- parsed = call_groq(client, user_prompt)
94
  bug_type = parsed.get("bug_type", "other")
95
  diagnosis = parsed.get("diagnosis", "")
96
  fixed_code = parsed.get("fixed_code", "")
@@ -119,10 +116,10 @@ def run_single_task(client: OpenAI, task_id: str) -> dict:
119
  }
120
 
121
 
122
- def run_baseline_on_all_tasks(api_key: str) -> list:
123
  client = OpenAI(
124
  api_key=api_key,
125
- base_url=GROQ_BASE_URL,
126
  )
127
  results = []
128
  for task_id in [TASK_SHAPE_MISMATCH, TASK_TRAINING_COLLAPSE, TASK_DATA_LEAKAGE]:
@@ -134,16 +131,19 @@ def run_baseline_on_all_tasks(api_key: str) -> list:
134
 
135
 
136
  if __name__ == "__main__":
137
- api_key = os.environ.get("GROQ_API_KEY", "")
 
 
 
138
  if not api_key:
139
- print("ERROR: GROQ_API_KEY environment variable not set.")
140
- print("Set it with: set GROQ_API_KEY=your_key_here (Windows)")
141
  sys.exit(1)
142
 
143
  print(f"Running baseline with model: {MODEL}")
 
144
  print(f"Seed: {SEED}\n")
145
 
146
- results = run_baseline_on_all_tasks(api_key)
147
 
148
  print("\n=== BASELINE RESULTS ===")
149
  total = 0.0
 
1
  # server/baseline_inference.py
2
  """
3
+ Baseline inference script.
4
+ Uses API_BASE_URL and API_KEY environment variables injected by the validator.
5
+ Falls back to Groq if those are not set (local dev).
6
 
7
+ Model: llama-3.3-70b-versatile
 
 
 
 
8
  """
9
 
10
  import os
 
63
  Respond with JSON only."""
64
 
65
 
66
+ def call_llm(client: OpenAI, user_prompt: str) -> dict:
67
  response = client.chat.completions.create(
68
  model=MODEL,
69
  messages=[
 
87
  )
88
 
89
  try:
90
+ parsed = call_llm(client, user_prompt)
91
  bug_type = parsed.get("bug_type", "other")
92
  diagnosis = parsed.get("diagnosis", "")
93
  fixed_code = parsed.get("fixed_code", "")
 
116
  }
117
 
118
 
119
+ def run_baseline_on_all_tasks(api_key: str, base_url: str) -> list:
120
  client = OpenAI(
121
  api_key=api_key,
122
+ base_url=base_url,
123
  )
124
  results = []
125
  for task_id in [TASK_SHAPE_MISMATCH, TASK_TRAINING_COLLAPSE, TASK_DATA_LEAKAGE]:
 
131
 
132
 
133
  if __name__ == "__main__":
134
+ # Use injected proxy creds if available, fall back to Groq for local dev
135
+ api_key = os.environ.get("API_KEY") or os.environ.get("GROQ_API_KEY", "")
136
+ base_url = os.environ.get("API_BASE_URL") or GROQ_BASE_URL
137
+
138
  if not api_key:
139
+ print("ERROR: API_KEY (or GROQ_API_KEY) environment variable not set.")
 
140
  sys.exit(1)
141
 
142
  print(f"Running baseline with model: {MODEL}")
143
+ print(f"Base URL: {base_url}")
144
  print(f"Seed: {SEED}\n")
145
 
146
+ results = run_baseline_on_all_tasks(api_key, base_url)
147
 
148
  print("\n=== BASELINE RESULTS ===")
149
  total = 0.0