RAHUL-13 commited on
Commit
611a353
Β·
1 Parent(s): c9d588c

Phase 2 complete: Fixed HF API endpoint to router.huggingface.co and added environment setup

Browse files
Downloads/hackathon/meta/.env ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment Variables for Bug Report Structuring Inference
2
+ # Fill in these values with your actual API credentials
3
+
4
+ # LLM API Base URL - Hugging Face Router (updated endpoint)
5
+ API_BASE_URL=https://router.huggingface.co/
6
+
7
+ # Model identifier (must match your LLM provider)
8
+ MODEL_NAME=meta-llama/Llama-3.1-8B-Instruct
9
+
10
+ # Your Hugging Face API Token
11
+ # Get it from: https://huggingface.co/settings/tokens
12
+ HF_TOKEN=hf_your_actual_token_here
13
+
14
+ # Optional: Custom environment URL (default is provided)
15
+ ENV_URL=https://rahul-13-bug-report-structuring-env.hf.space
16
+ MUblGvkVFDVuWlXkVgfPulnfuDadWEGCWq
Downloads/hackathon/meta/.env.example ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment Variables for Bug Report Structuring Inference
2
+ # Copy this file to .env and fill in your actual values
3
+
4
+ # LLM API Configuration
5
+ # For Together AI, Hugging Face Inference, or vLLM
6
+ API_BASE_URL=https://api.together.xyz/v1
7
+ # or for local vLLM: http://localhost:8000/v1
8
+ # or for HF Inference: https://api-inference.huggingface.co/v1
9
+
10
+ # Model identifier
11
+ MODEL_NAME=meta-llama/Llama-3.1-8B-Instruct
12
+ # Other options:
13
+ # - meta-llama/Llama-3.2-70B-Instruct
14
+ # - meta-llama/Llama-2-13b-chat
15
+ # - mistralai/Mistral-7B-Instruct-v0.3
16
+
17
+ # Hugging Face API Token
18
+ # Get this from https://huggingface.co/settings/tokens
19
+ HF_TOKEN=hf_your_token_here
20
+
21
+ # Optional: Custom environment URL
22
+ ENV_URL=https://rahul-13-bug-report-structuring-env.hf.space
Downloads/hackathon/meta/SETUP.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # πŸ”§ Fix: Missing Environment Variables Error
2
+
3
+ ## Problem
4
+ Your `inference.py` is failing because it can't find these environment variables:
5
+ - `API_BASE_URL` - URL to your LLM API
6
+ - `MODEL_NAME` - Model identifier
7
+ - `HF_TOKEN` - Hugging Face authentication token
8
+
9
+ ## Solution
10
+
11
+ ### Step 1: Create/Edit the `.env` file
12
+ A `.env` file has been created in your project root. Edit it with your actual credentials:
13
+
14
+ ```bash
15
+ # Open .env in your editor and fill in:
16
+ API_BASE_URL=https://api.together.xyz/v1 # Your LLM API endpoint
17
+ MODEL_NAME=meta-llama/Llama-3.1-8B-Instruct # Model you want to use
18
+ HF_TOKEN=hf_xxxxxxxxxxxxxxxxxxxxx # Your HF token from https://huggingface.co/settings/tokens
19
+ ```
20
+
21
+ ### Step 2: Verify Your Setup
22
+ Run the verification script to check if everything is configured:
23
+
24
+ ```bash
25
+ python verify_env.py
26
+ ```
27
+
28
+ Expected output:
29
+ ```
30
+ βœ… .env file found
31
+ βœ… API_BASE_URL: https://api.together.xyz/v1
32
+ βœ… MODEL_NAME: meta-llama/...
33
+ βœ… HF_TOKEN: hf_xxxx...xxxxx
34
+ βœ… All dependencies installed
35
+ βœ… All checks passed! Ready to run inference.py
36
+ ```
37
+
38
+ ### Step 3: Run Inference
39
+ Once verification passes, run your inference:
40
+
41
+ ```bash
42
+ python inference.py
43
+ ```
44
+
45
+ ## Environment Variable Options
46
+
47
+ ### API_BASE_URL (choose one):
48
+
49
+ **Option 1: Together AI** (Recommended for hackathons)
50
+ ```
51
+ API_BASE_URL=https://api.together.xyz/v1
52
+ ```
53
+ - Free tier available
54
+ - Sign up at: https://api.together.xyz
55
+
56
+ **Option 2: Hugging Face Inference**
57
+ ```
58
+ API_BASE_URL=https://api-inference.huggingface.co/v1
59
+ ```
60
+ - Use your HF token for authentication
61
+ - Limited free tier
62
+
63
+ **Option 3: Local vLLM Server** (Advanced)
64
+ ```
65
+ API_BASE_URL=http://localhost:8000/v1
66
+ ```
67
+ - Requires running vLLM locally
68
+ - Best for development
69
+
70
+ ### MODEL_NAME (examples):
71
+ - `meta-llama/Llama-3.1-8B-Instruct` βœ… Recommended
72
+ - `meta-llama/Llama-3.2-70B-Instruct` (more powerful)
73
+ - `mistralai/Mistral-7B-Instruct-v0.3`
74
+ - `NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO`
75
+
76
+ ### HF_TOKEN:
77
+ 1. Go to https://huggingface.co/settings/tokens
78
+ 2. Click "New token"
79
+ 3. Select "Read" permission
80
+ 4. Copy the token and paste in `.env`
81
+
82
+ ## Common Issues
83
+
84
+ **❌ "curl: (6) Could not resolve host"**
85
+ - Check your `API_BASE_URL` is correct and accessible
86
+ - Test: `curl {API_BASE_URL}/models`
87
+
88
+ **❌ "401 Unauthorized" or "invalid_api_key"**
89
+ - Your `HF_TOKEN` is wrong or expired
90
+ - Generate a new token at https://huggingface.co/settings/tokens
91
+
92
+ **❌ "Model not found"**
93
+ - Check your `MODEL_NAME` matches the provider's available models
94
+ - Visit the provider's documentation
95
+
96
+ ## How It Works
97
+
98
+ After the changes made to `inference.py`:
99
+ 1. The script automatically loads variables from `.env` file (if exists)
100
+ 2. Then it checks for required environment variables
101
+ 3. If any are missing, it shows a helpful error message
102
+ 4. If all are set, it proceeds with inference
103
+
104
+ This means you can:
105
+ - Use `.env` file (checked automatically)
106
+ - Export variables manually: `export API_BASE_URL=...`
107
+ - Mix both approaches (manual exports override `.env`)
108
+
109
+ ## Quick Commands (PowerShell)
110
+
111
+ ```powershell
112
+ # Edit .env file
113
+ code .env
114
+
115
+ # Verify environment
116
+ python verify_env.py
117
+
118
+ # Run inference (after .env is filled in)
119
+ python inference.py
120
+ ```
121
+
122
+ ## Next Steps for Phase 2
123
+
124
+ 1. βœ… Fill in `.env` with your credentials
125
+ 2. βœ… Run `python verify_env.py` to confirm setup
126
+ 3. βœ… Run `python inference.py` to complete phase 2
127
+ 4. βœ… Check `inference_results.txt` for logs an results
Downloads/hackathon/meta/inference.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Bug Report Structuring Environment - Inference Script
4
+
5
+ This script runs the LLM agent against the Bug Report Structuring Environment.
6
+ It connects to the deployed environment (HF Space), uses an LLM to structure
7
+ messy bug reports, and logs results in the required OpenEnv format.
8
+
9
+ Required environment variables:
10
+ API_BASE_URL β€” Base URL for the LLM API (e.g., vLLM or HF Inference)
11
+ MODEL_NAME β€” Model identifier (e.g., meta-llama/Llama-3.1-8B-Instruct)
12
+ HF_TOKEN β€” Hugging Face authentication token
13
+
14
+ Log format (STDOUT):
15
+ [START] task=<task> env=<env> model=<model>
16
+ [STEP] step=<n> action=<summary> reward=<0.00> done=<bool> error=<msg|null>
17
+ [END] success=<bool> steps=<n> score=<0.00> rewards=<r1,r2,...>
18
+ """
19
+
20
+ import os
21
+ import sys
22
+ import json
23
+ import time
24
+ import requests
25
+ from openai import OpenAI
26
+ from pathlib import Path
27
+
28
+ # ─── Load Environment Variables from .env if it exists ───────────
29
+ env_file = Path(__file__).parent / ".env"
30
+ if env_file.exists():
31
+ with open(env_file) as f:
32
+ for line in f:
33
+ line = line.strip()
34
+ if line and not line.startswith("#"):
35
+ key, _, value = line.partition("=")
36
+ key = key.strip()
37
+ value = value.strip()
38
+ if key and value:
39
+ os.environ.setdefault(key, value)
40
+
41
+ # ─── Configuration ────────────────────────────────────────────────
42
+
43
+ API_BASE_URL = os.environ.get("API_BASE_URL", "")
44
+ MODEL_NAME = os.environ.get("MODEL_NAME", "")
45
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
46
+
47
+ # Environment URL (the deployed HF Space)
48
+ ENV_URL = os.environ.get(
49
+ "ENV_URL",
50
+ "https://rahul-13-bug-report-structuring-env.hf.space"
51
+ )
52
+
53
+ BENCHMARK_NAME = "bug_report_structuring"
54
+ TASKS = ["easy", "medium", "hard"]
55
+ MAX_RETRIES = 2
56
+
57
+ # ─── LLM Client Setup ────────────────────────────────────────────
58
+
59
+ client = OpenAI(
60
+ base_url=API_BASE_URL,
61
+ api_key=HF_TOKEN,
62
+ )
63
+
64
+
65
+ # ─── Prompt Templates ────────────────────────────────────────────
66
+
67
+ SYSTEM_PROMPT = """You are an expert bug report analyst. Your job is to take messy, unstructured bug reports and convert them into well-organized, structured formats.
68
+
69
+ You must output a valid JSON object with exactly these fields:
70
+ - "title": A clear, concise title summarizing the bug
71
+ - "steps_to_reproduce": Numbered step-by-step instructions to reproduce the bug
72
+ - "expected_behavior": What should happen (correct behavior)
73
+ - "actual_behavior": What actually happens (the bug symptoms)
74
+ - "severity": One of "low", "medium", "high", or "critical"
75
+ - "environment": OS, browser, version, platform details
76
+ - "additional_notes": Any other relevant details
77
+
78
+ Rules:
79
+ 1. Extract ALL information from the original report - don't miss details
80
+ 2. Use professional, clear language
81
+ 3. Steps should be specific and actionable
82
+ 4. Include version numbers, error messages, and technical details
83
+ 5. Severity should reflect the actual impact described
84
+ 6. Output ONLY the JSON object, no other text or markdown"""
85
+
86
+ REFINEMENT_PROMPT = """You previously structured a bug report but the grading feedback indicates room for improvement.
87
+
88
+ Original messy bug report:
89
+ {raw_report}
90
+
91
+ Your previous submission scored {score:.2f}/1.00.
92
+
93
+ Feedback:
94
+ {feedback}
95
+
96
+ Previous field scores:
97
+ {field_scores}
98
+
99
+ Please submit an improved version. Focus on the fields with low scores.
100
+ Output ONLY a valid JSON object with the same fields: title, steps_to_reproduce, expected_behavior, actual_behavior, severity, environment, additional_notes."""
101
+
102
+
103
+ # ─── Helper Functions ─────────────────────────────────────────────
104
+
105
+ def call_llm(messages: list) -> str:
106
+ """Call the LLM and return the response text."""
107
+ try:
108
+ response = client.chat.completions.create(
109
+ model=MODEL_NAME,
110
+ messages=messages,
111
+ temperature=0.3,
112
+ max_tokens=2048,
113
+ )
114
+ return response.choices[0].message.content.strip()
115
+ except Exception as e:
116
+ print(f" [LLM ERROR] {e}", file=sys.stderr)
117
+ return ""
118
+
119
+
120
+ def parse_json_response(text: str) -> dict:
121
+ """Parse JSON from LLM response, handling markdown code blocks."""
122
+ # Strip markdown code blocks if present
123
+ if "```json" in text:
124
+ text = text.split("```json")[1].split("```")[0].strip()
125
+ elif "```" in text:
126
+ text = text.split("```")[1].split("```")[0].strip()
127
+
128
+ try:
129
+ return json.loads(text)
130
+ except json.JSONDecodeError:
131
+ # Try to find JSON object in the text
132
+ start = text.find("{")
133
+ end = text.rfind("}") + 1
134
+ if start >= 0 and end > start:
135
+ try:
136
+ return json.loads(text[start:end])
137
+ except json.JSONDecodeError:
138
+ pass
139
+ return {}
140
+
141
+
142
+ def env_reset(task_id: str) -> dict:
143
+ """Call the environment's reset endpoint."""
144
+ try:
145
+ resp = requests.post(
146
+ f"{ENV_URL}/reset",
147
+ json={"task_id": task_id},
148
+ timeout=30,
149
+ )
150
+ resp.raise_for_status()
151
+ return resp.json()
152
+ except Exception as e:
153
+ print(f" [ENV ERROR] Reset failed: {e}", file=sys.stderr)
154
+ return {}
155
+
156
+
157
+ def env_step(action: dict) -> dict:
158
+ """Call the environment's step endpoint."""
159
+ try:
160
+ resp = requests.post(
161
+ f"{ENV_URL}/step",
162
+ json={"action": action},
163
+ timeout=30,
164
+ )
165
+ resp.raise_for_status()
166
+ return resp.json()
167
+ except Exception as e:
168
+ print(f" [ENV ERROR] Step failed: {e}", file=sys.stderr)
169
+ return {}
170
+
171
+
172
+ def make_default_action() -> dict:
173
+ """Return a minimal valid action as fallback."""
174
+ return {
175
+ "title": "Bug Report",
176
+ "steps_to_reproduce": "1. See the bug report",
177
+ "expected_behavior": "Application works correctly",
178
+ "actual_behavior": "Application does not work as expected",
179
+ "severity": "medium",
180
+ "environment": "Not specified",
181
+ "additional_notes": "",
182
+ }
183
+
184
+
185
+ # ─── Main Inference Loop ─────────────────────────────────────────
186
+
187
+ def run_task(task_id: str) -> dict:
188
+ """
189
+ Run the agent on a single task.
190
+
191
+ Returns dict with: success, steps, score, rewards
192
+ """
193
+ # ── START ──
194
+ print(f"[START] task={task_id} env={BENCHMARK_NAME} model={MODEL_NAME}")
195
+
196
+ rewards = []
197
+ best_score = 0.0
198
+ step_count = 0
199
+ success = False
200
+
201
+ # Reset environment
202
+ obs = env_reset(task_id)
203
+ if not obs:
204
+ print(f"[STEP] step=1 action=reset_failed reward=0.00 done=true error=environment_reset_failed")
205
+ print(f"[END] success=false steps=1 score=0.00 rewards=0.00")
206
+ return {"success": False, "steps": 1, "score": 0.0, "rewards": [0.0]}
207
+
208
+ raw_report = obs.get("raw_report", "")
209
+ max_steps = obs.get("max_steps", 3)
210
+
211
+ # ── First submission ──
212
+ messages = [
213
+ {"role": "system", "content": SYSTEM_PROMPT},
214
+ {"role": "user", "content": f"Structure this bug report:\n\n{raw_report}"},
215
+ ]
216
+
217
+ llm_response = call_llm(messages)
218
+ action = parse_json_response(llm_response)
219
+
220
+ if not action or "title" not in action:
221
+ action = make_default_action()
222
+
223
+ # Ensure all fields exist
224
+ for field in ["title", "steps_to_reproduce", "expected_behavior",
225
+ "actual_behavior", "severity", "environment", "additional_notes"]:
226
+ if field not in action:
227
+ action[field] = ""
228
+
229
+ step_count = 1
230
+ result = env_step(action)
231
+
232
+ if result:
233
+ score = result.get("score", 0.0)
234
+ reward = result.get("reward", 0.0)
235
+ done = result.get("done", False)
236
+ error = "null"
237
+ else:
238
+ score = 0.0
239
+ reward = 0.0
240
+ done = True
241
+ error = "step_request_failed"
242
+
243
+ rewards.append(reward)
244
+ best_score = max(best_score, score)
245
+ action_summary = action.get("title", "structured_report")[:50].replace(" ", "_")
246
+
247
+ print(
248
+ f"[STEP] step={step_count} action={action_summary} "
249
+ f"reward={reward:.2f} done={str(done).lower()} error={error}"
250
+ )
251
+
252
+ # ── Refinement steps ──
253
+ while not done and step_count < max_steps:
254
+ feedback = result.get("feedback", "")
255
+ field_scores = result.get("field_scores", {})
256
+
257
+ refinement_content = REFINEMENT_PROMPT.format(
258
+ raw_report=raw_report,
259
+ score=score,
260
+ feedback=feedback,
261
+ field_scores=json.dumps(field_scores, indent=2),
262
+ )
263
+
264
+ messages = [
265
+ {"role": "system", "content": SYSTEM_PROMPT},
266
+ {"role": "user", "content": refinement_content},
267
+ ]
268
+
269
+ llm_response = call_llm(messages)
270
+ action = parse_json_response(llm_response)
271
+
272
+ if not action or "title" not in action:
273
+ action = make_default_action()
274
+
275
+ for field in ["title", "steps_to_reproduce", "expected_behavior",
276
+ "actual_behavior", "severity", "environment", "additional_notes"]:
277
+ if field not in action:
278
+ action[field] = ""
279
+
280
+ step_count += 1
281
+ result = env_step(action)
282
+
283
+ if result:
284
+ score = result.get("score", 0.0)
285
+ reward = result.get("reward", 0.0)
286
+ done = result.get("done", False)
287
+ error = "null"
288
+ else:
289
+ score = 0.0
290
+ reward = 0.0
291
+ done = True
292
+ error = "step_request_failed"
293
+
294
+ rewards.append(reward)
295
+ best_score = max(best_score, score)
296
+ action_summary = action.get("title", "refined_report")[:50].replace(" ", "_")
297
+
298
+ print(
299
+ f"[STEP] step={step_count} action={action_summary} "
300
+ f"reward={reward:.2f} done={str(done).lower()} error={error}"
301
+ )
302
+
303
+ # ── END ──
304
+ success = best_score >= 0.6
305
+ rewards_str = ",".join(f"{r:.2f}" for r in rewards)
306
+
307
+ print(
308
+ f"[END] success={str(success).lower()} steps={step_count} "
309
+ f"score={best_score:.2f} rewards={rewards_str}"
310
+ )
311
+
312
+ return {
313
+ "success": success,
314
+ "steps": step_count,
315
+ "score": best_score,
316
+ "rewards": rewards,
317
+ }
318
+
319
+
320
+ def main():
321
+ """Run inference on all tasks."""
322
+ # Validate environment variables
323
+ missing = []
324
+ if not API_BASE_URL:
325
+ missing.append("API_BASE_URL")
326
+ if not MODEL_NAME:
327
+ missing.append("MODEL_NAME")
328
+ if not HF_TOKEN:
329
+ missing.append("HF_TOKEN")
330
+
331
+ if missing:
332
+ print(f"❌ Missing environment variables: {', '.join(missing)}", file=sys.stderr)
333
+ print("Set them before running:", file=sys.stderr)
334
+ print(" export API_BASE_URL=https://...", file=sys.stderr)
335
+ print(" export MODEL_NAME=meta-llama/...", file=sys.stderr)
336
+ print(" export HF_TOKEN=hf_...", file=sys.stderr)
337
+ sys.exit(1)
338
+
339
+ print(f"═══ Bug Report Structuring - Inference ═══", file=sys.stderr)
340
+ print(f" Model: {MODEL_NAME}", file=sys.stderr)
341
+ print(f" Env: {ENV_URL}", file=sys.stderr)
342
+ print(f" Tasks: {TASKS}", file=sys.stderr)
343
+ print(f"═══════════════════════════════════════════", file=sys.stderr)
344
+
345
+ results = {}
346
+ total_score = 0.0
347
+ start_time = time.time()
348
+
349
+ for task_id in TASKS:
350
+ print(f"\n--- Task: {task_id} ---", file=sys.stderr)
351
+ result = run_task(task_id)
352
+ results[task_id] = result
353
+ total_score += result["score"]
354
+ print(f" Score: {result['score']:.2f}", file=sys.stderr)
355
+
356
+ elapsed = time.time() - start_time
357
+ avg_score = total_score / len(TASKS)
358
+
359
+ print(f"\n═══ Summary ═══", file=sys.stderr)
360
+ print(f" Average Score: {avg_score:.2f}", file=sys.stderr)
361
+ print(f" Time Elapsed: {elapsed:.1f}s", file=sys.stderr)
362
+ for task_id, result in results.items():
363
+ status = "βœ…" if result["success"] else "❌"
364
+ print(
365
+ f" {status} {task_id}: {result['score']:.2f} "
366
+ f"({result['steps']} steps)",
367
+ file=sys.stderr,
368
+ )
369
+ print(f"═══════════════", file=sys.stderr)
370
+
371
+
372
+ if __name__ == "__main__":
373
+ main()
Downloads/hackathon/meta/pyproject.toml CHANGED
@@ -24,11 +24,12 @@ classifiers = [
24
  ]
25
 
26
  dependencies = [
27
- "fastapi==0.115.6",
28
- "uvicorn==0.34.0",
29
- "pydantic==2.10.4",
30
- "requests==2.32.3",
31
- "openai==1.58.1",
 
32
  ]
33
 
34
  [project.optional-dependencies]
@@ -37,12 +38,15 @@ dev = [
37
  "pytest-cov>=3.0",
38
  ]
39
 
 
 
 
40
  [project.urls]
41
  Repository = "https://github.com/SAI-RAHUL-ROKKAM/meta_hack"
42
  Documentation = "https://huggingface.co/spaces/RAHUL-13/bug-report-structuring-env"
43
 
44
  [tool.setuptools]
45
- packages = ["src"]
46
 
47
  [tool.pytest.ini_options]
48
  testpaths = ["tests"]
 
24
  ]
25
 
26
  dependencies = [
27
+ "fastapi>=0.115.0",
28
+ "uvicorn>=0.34.0",
29
+ "pydantic>=2.10.0",
30
+ "requests>=2.32.0",
31
+ "openai>=1.58.0",
32
+ "openenv-core>=0.2.0",
33
  ]
34
 
35
  [project.optional-dependencies]
 
38
  "pytest-cov>=3.0",
39
  ]
40
 
41
+ [project.scripts]
42
+ server = "server.app:main"
43
+
44
  [project.urls]
45
  Repository = "https://github.com/SAI-RAHUL-ROKKAM/meta_hack"
46
  Documentation = "https://huggingface.co/spaces/RAHUL-13/bug-report-structuring-env"
47
 
48
  [tool.setuptools]
49
+ packages = ["server"]
50
 
51
  [tool.pytest.ini_options]
52
  testpaths = ["tests"]
Downloads/hackathon/meta/verify_env.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Verify that the environment is properly configured for running inference.
4
+ Run this script before running inference.py to catch configuration issues early.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ def check_env_file():
12
+ """Check if .env file exists and has required variables."""
13
+ env_file = Path(__file__).parent / ".env"
14
+
15
+ if not env_file.exists():
16
+ print("❌ .env file not found")
17
+ print(f" Create it at: {env_file}")
18
+ return False
19
+
20
+ print("βœ… .env file found")
21
+ return True
22
+
23
+ def check_env_variables():
24
+ """Check if required environment variables are set."""
25
+ required_vars = ["API_BASE_URL", "MODEL_NAME", "HF_TOKEN"]
26
+ missing = []
27
+
28
+ for var in required_vars:
29
+ value = os.environ.get(var, "").strip()
30
+ if not value:
31
+ missing.append(var)
32
+ print(f"❌ {var}: NOT SET")
33
+ else:
34
+ # Show masked value for security
35
+ masked = f"{value[:10]}...{value[-5:]}" if len(value) > 20 else value
36
+ print(f"βœ… {var}: {masked}")
37
+
38
+ return len(missing) == 0
39
+
40
+ def load_env_file():
41
+ """Load .env file into environment."""
42
+ env_file = Path(__file__).parent / ".env"
43
+ if env_file.exists():
44
+ with open(env_file) as f:
45
+ for line in f:
46
+ line = line.strip()
47
+ if line and not line.startswith("#"):
48
+ key, _, value = line.partition("=")
49
+ key = key.strip()
50
+ value = value.strip()
51
+ if key and value:
52
+ os.environ[key] = value
53
+
54
+ def check_dependencies():
55
+ """Check if required packages are installed."""
56
+ print("\nChecking dependencies...")
57
+ required = ["openai", "requests", "fastapi", "uvicorn", "pydantic"]
58
+ missing = []
59
+
60
+ for package in required:
61
+ try:
62
+ __import__(package)
63
+ print(f"βœ… {package}: installed")
64
+ except ImportError:
65
+ missing.append(package)
66
+ print(f"❌ {package}: NOT INSTALLED")
67
+
68
+ return len(missing) == 0
69
+
70
+ def main():
71
+ print("═══ Environment Verification ═══\n")
72
+
73
+ # Load .env file first
74
+ load_env_file()
75
+
76
+ # Check .env file
77
+ has_env_file = check_env_file()
78
+
79
+ print("\nChecking environment variables...")
80
+ has_all_vars = check_env_variables()
81
+
82
+ # Check dependencies
83
+ has_deps = check_dependencies()
84
+
85
+ print("\n" + "═" * 35)
86
+
87
+ if has_all_vars and has_deps:
88
+ print("βœ… All checks passed! Ready to run inference.py")
89
+ return 0
90
+ else:
91
+ print("❌ Some checks failed. Please fix the issues above.")
92
+ print("\nQuick fix:")
93
+ print("1. Edit .env file with your actual credentials")
94
+ print("2. Run: pip install -r requirements.txt")
95
+ return 1
96
+
97
+ if __name__ == "__main__":
98
+ sys.exit(main())