s1144662 commited on
Commit
bdd0210
ยท
verified ยท
1 Parent(s): 287b0f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -81
app.py CHANGED
@@ -4,164 +4,221 @@ import requests
4
  import pandas as pd
5
  from typing import Optional
6
 
7
- # --- Constants ---
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
- HF_API_URL = "https://api-inference.huggingface.co/models"
10
 
11
- class BasicAgent:
 
12
  def __init__(self):
13
- """็”จ HuggingFace Inference API"""
14
- self.hf_token = os.getenv("HF_TOKEN")
15
- # ๆ”น็”จๆ›ด็ฉฉๅฎš็š„ๅฐๆจกๅž‹
16
- self.model_name = "google/flan-t5-base"
17
-
18
-
19
- if not self.hf_token:
20
- print("โœ— HF_TOKEN not found")
21
  self.agent = None
22
  return
23
 
24
- self.agent_url = f"{HF_API_URL}/{self.model_name}"
25
  self.agent = True
26
- print(f"โœ“ Agent initialized with model: {self.model_name}")
27
-
28
  def __call__(self, question: str) -> str:
29
- """้€้Ž HF Inference API ๅ‘ผๅซๆจกๅž‹"""
30
  if self.agent is None:
31
- return "HF_TOKEN not configured!"
32
 
33
  try:
34
- headers = {"Authorization": f"Bearer {self.hf_token}"}
 
 
 
35
 
36
  payload = {
37
- "inputs": question,
38
- "parameters": {
39
- "max_new_tokens": 256,
40
- }
 
 
 
 
 
 
 
 
 
 
41
  }
42
 
43
  response = requests.post(
44
- self.agent_url,
45
  headers=headers,
46
  json=payload,
47
- timeout=60
48
  )
49
 
50
- if response.status_code == 410:
51
- return "Model loading... please try again"
52
-
53
  if response.status_code != 200:
54
- return f"API Error {response.status_code}: {response.text[:100]}"
 
55
 
56
  result = response.json()
 
57
 
58
- if isinstance(result, list) and len(result) > 0:
59
- answer = result[0].get("generated_text", "")
60
- answer = answer.replace(question, "").strip()
61
- return answer[:1000] if answer else "No answer generated"
62
-
63
- return "Invalid response format"
64
 
 
 
 
 
65
  except Exception as e:
66
- return f"Error: {str(e)[:100]}"
67
 
68
 
69
  def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
70
  """ไธป่ฆ่ฉ•ไผฐๅ’Œๆไบคๅ‡ฝๆ•ธ"""
71
 
 
72
  if profile is None:
73
- return "Please Login to Hugging Face with the button.", None
74
 
75
  username = profile.username
76
  space_id = os.getenv("SPACE_ID", "s1144662")
77
-
78
  api_url = DEFAULT_API_URL
79
- questions_url = f"{api_url}/questions"
80
- submit_url = f"{api_url}/submit"
81
-
82
  try:
83
- agent = BasicAgent()
 
 
84
  except Exception as e:
85
- return f"Error: {str(e)}", None
86
-
87
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
88
-
89
  try:
90
- response = requests.get(questions_url, timeout=30)
 
91
  response.raise_for_status()
92
  questions_data = response.json()
 
93
  except Exception as e:
94
- return f"Error fetching questions: {str(e)}", None
95
 
96
  answers_payload = []
97
  results_log = []
98
-
99
  total = len(questions_data)
 
 
100
  for idx, item in enumerate(questions_data, 1):
101
  task_id = item.get("task_id")
102
  question_text = item.get("question")
103
 
104
- print(f"[{idx}/{total}] Processing...")
105
 
106
  try:
107
- submitted_answer = agent(question_text)
 
108
  answers_payload.append({
109
- "task_id": task_id,
110
- "submitted_answer": submitted_answer
111
  })
 
112
  results_log.append({
113
- "Task ID": task_id,
114
- "Question": question_text[:80],
115
- "Answer": submitted_answer[:200]
116
  })
 
117
  except Exception as e:
 
118
  answers_payload.append({
119
- "task_id": task_id,
120
- "submitted_answer": str(e)
121
  })
122
  results_log.append({
123
- "Task ID": task_id,
124
- "Question": question_text[:80],
125
- "Answer": str(e)[:100]
126
  })
127
 
128
- submission_data = {
129
- "username": username,
130
- "agent_code": agent_code,
131
- "answers": answers_payload
132
- }
133
-
134
  try:
135
- response = requests.post(submit_url, json=submission_data, timeout=120)
 
 
 
 
 
 
 
 
 
 
 
136
  response.raise_for_status()
137
- result_data = response.json()
138
 
139
- score = result_data.get('score', 'N/A')
140
- correct = result_data.get('correct_count', 0)
141
- total_q = result_data.get('total_attempted', 0)
142
- status_msg = f"โœ“ Score: {score}% ({correct}/{total_q} correct)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  except Exception as e:
144
- status_msg = f"โœ— Submission Failed: {str(e)}"
145
 
146
  return status_msg, pd.DataFrame(results_log)
147
 
148
 
149
- with gr.Blocks(title="Unit 4 Final Assignment") as demo:
150
- gr.Markdown("# Unit 4 Final Project: AI Agent")
151
- gr.Markdown("_Using Hugging Face Inference API_")
 
 
 
 
 
152
 
153
  with gr.Row():
154
  gr.LoginButton(scale=1)
155
- run_button = gr.Button("Run Evaluation & Submit All Answers", scale=2, variant="primary")
156
 
157
- status_output = gr.Textbox(label="Result", lines=3, interactive=False)
158
- results_table = gr.DataFrame(label="Details", interactive=False)
159
-
160
- run_button.click(
 
 
161
  fn=run_and_submit_all,
162
  inputs=[],
163
- outputs=[status_output, results_table]
164
  )
 
 
 
 
 
 
 
 
165
 
166
  if __name__ == "__main__":
167
  demo.launch(debug=True)
 
4
  import pandas as pd
5
  from typing import Optional
6
 
 
7
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
8
+ GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
9
 
10
+ class GroqAgent:
11
+ """ไฝฟ็”จ Groq API ็š„ LLM Agent"""
12
  def __init__(self):
13
+ self.api_key = os.getenv("GROQ_API_KEY")
14
+ if not self.api_key:
15
+ print("โœ— GROQ_API_KEY not found in environment variables")
 
 
 
 
 
16
  self.agent = None
17
  return
18
 
 
19
  self.agent = True
20
+ print("โœ“ Groq agent initialized successfully")
21
+
22
  def __call__(self, question: str) -> str:
23
+ """ๅ›ž็ญ”ๅ•้กŒ"""
24
  if self.agent is None:
25
+ return "Error: GROQ_API_KEY not configured. Please add it to Secrets."
26
 
27
  try:
28
+ headers = {
29
+ "Authorization": f"Bearer {self.api_key}",
30
+ "Content-Type": "application/json"
31
+ }
32
 
33
  payload = {
34
+ "model": "llama-3.3-70b-versatile",
35
+ "messages": [
36
+ {
37
+ "role": "system",
38
+ "content": "You are a helpful AI assistant. Answer questions accurately and concisely. Provide direct answers without unnecessary explanation."
39
+ },
40
+ {
41
+ "role": "user",
42
+ "content": question
43
+ }
44
+ ],
45
+ "temperature": 0.2,
46
+ "max_tokens": 500,
47
+ "top_p": 0.9
48
  }
49
 
50
  response = requests.post(
51
+ GROQ_API_URL,
52
  headers=headers,
53
  json=payload,
54
+ timeout=30
55
  )
56
 
 
 
 
57
  if response.status_code != 200:
58
+ error_msg = response.text[:200] if response.text else "Unknown error"
59
+ return f"API Error {response.status_code}: {error_msg}"
60
 
61
  result = response.json()
62
+ answer = result['choices'][0]['message']['content'].strip()
63
 
64
+ # ้™ๅˆถ็ญ”ๆกˆ้•ทๅบฆ
65
+ return answer[:1000] if answer else "Unable to generate answer"
 
 
 
 
66
 
67
+ except requests.exceptions.Timeout:
68
+ return "Request timeout - please try again"
69
+ except requests.exceptions.RequestException as e:
70
+ return f"Network error: {str(e)[:100]}"
71
  except Exception as e:
72
+ return f"Error: {str(e)[:150]}"
73
 
74
 
75
  def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
76
  """ไธป่ฆ่ฉ•ไผฐๅ’Œๆไบคๅ‡ฝๆ•ธ"""
77
 
78
+ # ๆชขๆŸฅ็™ปๅ…ฅ
79
  if profile is None:
80
+ return "โš ๏ธ Please click 'Login with Hugging Face' button first!", None
81
 
82
  username = profile.username
83
  space_id = os.getenv("SPACE_ID", "s1144662")
 
84
  api_url = DEFAULT_API_URL
85
+
86
+ # ๅˆๅง‹ๅŒ– Agent
 
87
  try:
88
+ agent = GroqAgent()
89
+ if agent.agent is None:
90
+ return "โŒ Error: GROQ_API_KEY not found!\n\nPlease add your Groq API key to Secrets:\n1. Go to Settings โ†’ Secrets\n2. Add: GROQ_API_KEY=gsk_your_key", None
91
  except Exception as e:
92
+ return f"โŒ Agent initialization failed: {str(e)}", None
93
+
94
+ # ็ฒๅ–ๅ•้กŒ
 
95
  try:
96
+ print("Fetching questions...")
97
+ response = requests.get(f"{api_url}/questions", timeout=30)
98
  response.raise_for_status()
99
  questions_data = response.json()
100
+ print(f"โœ“ Got {len(questions_data)} questions")
101
  except Exception as e:
102
+ return f"โŒ Failed to fetch questions: {str(e)}", None
103
 
104
  answers_payload = []
105
  results_log = []
106
+
107
  total = len(questions_data)
108
+
109
+ # ๅ›ž็ญ”ๆฏๅ€‹ๅ•้กŒ
110
  for idx, item in enumerate(questions_data, 1):
111
  task_id = item.get("task_id")
112
  question_text = item.get("question")
113
 
114
+ print(f"[{idx}/{total}] Processing: {task_id[:8]}...")
115
 
116
  try:
117
+ answer = agent(question_text)
118
+
119
  answers_payload.append({
120
+ "task_id": task_id,
121
+ "submitted_answer": answer
122
  })
123
+
124
  results_log.append({
125
+ "Task ID": task_id[:12] + "...",
126
+ "Question": question_text[:70] + "...",
127
+ "Answer": answer[:150] + ("..." if len(answer) > 150 else "")
128
  })
129
+
130
  except Exception as e:
131
+ error_msg = str(e)[:100]
132
  answers_payload.append({
133
+ "task_id": task_id,
134
+ "submitted_answer": f"Error: {error_msg}"
135
  })
136
  results_log.append({
137
+ "Task ID": task_id[:12] + "...",
138
+ "Question": question_text[:70] + "...",
139
+ "Answer": f"Error: {error_msg}"
140
  })
141
 
142
+ # ๆไบค็ญ”ๆกˆ
 
 
 
 
 
143
  try:
144
+ print("Submitting answers...")
145
+ submission_data = {
146
+ "username": username,
147
+ "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
148
+ "answers": answers_payload
149
+ }
150
+
151
+ response = requests.post(
152
+ f"{api_url}/submit",
153
+ json=submission_data,
154
+ timeout=120
155
+ )
156
  response.raise_for_status()
157
+ data = response.json()
158
 
159
+ score = data.get('score', 0)
160
+ correct = data.get('correct_count', 0)
161
+ total_q = data.get('total_attempted', 0)
162
+
163
+ print(f"โœ“ Score: {score}% ({correct}/{total_q})")
164
+
165
+ # ็”Ÿๆˆ็ตๆžœ่จŠๆฏ
166
+ if score >= 30:
167
+ status_msg = f"""๐ŸŽ‰ CONGRATULATIONS! YOU PASSED! ๐ŸŽ‰
168
+
169
+ ๐Ÿ“Š Final Score: {score}% ({correct}/{total_q} correct)
170
+ โœ… Required: 30% (You exceeded it!)
171
+
172
+ ๐ŸŽ“ Next Step: Get Your Certificate
173
+ ๐Ÿ‘‰ Visit: https://huggingface.co/spaces/agents-course/Unit4-Final-Certificate
174
+
175
+ Great job! ๐Ÿš€"""
176
+ else:
177
+ status_msg = f"""๐Ÿ“Š Score: {score}% ({correct}/{total_q} correct)
178
+ โŒ Required: 30% to pass
179
+ ๐Ÿ“ˆ You need {int((30 * total_q / 100) - correct)} more correct answers
180
+
181
+ ๐Ÿ’ก Try running again - different prompts may improve results."""
182
+
183
+ except requests.exceptions.RequestException as e:
184
+ status_msg = f"โŒ Submission failed (network error): {str(e)[:200]}"
185
  except Exception as e:
186
+ status_msg = f"โŒ Submission failed: {str(e)[:200]}"
187
 
188
  return status_msg, pd.DataFrame(results_log)
189
 
190
 
191
+ # Gradio ไป‹้ข
192
+ with gr.Blocks(title="Unit 4 Final Assignment", theme=gr.themes.Soft()) as demo:
193
+ gr.Markdown("""
194
+ # ๐ŸŽ“ Unit 4 Final Project: AI Agent
195
+
196
+ ### Using Groq API (Llama 3.3 70B)
197
+ **Goal**: Score โ‰ฅ 30% to get certificate
198
+ """)
199
 
200
  with gr.Row():
201
  gr.LoginButton(scale=1)
202
+ run_btn = gr.Button("๐Ÿš€ Run Evaluation & Submit All Answers", scale=3, variant="primary")
203
 
204
+ gr.Markdown("---")
205
+
206
+ status = gr.Textbox(label="๐Ÿ“Š Submission Status", lines=8, interactive=False)
207
+ details = gr.DataFrame(label="๐Ÿ“ Detailed Results", interactive=False)
208
+
209
+ run_btn.click(
210
  fn=run_and_submit_all,
211
  inputs=[],
212
+ outputs=[status, details]
213
  )
214
+
215
+ gr.Markdown("""
216
+ ---
217
+ ### ๐Ÿ’ก Tips
218
+ - Make sure you've added `GROQ_API_KEY` to Secrets (Settings โ†’ Secrets)
219
+ - Get free API key at: https://console.groq.com/
220
+ - If score < 30%, you can try running again
221
+ """)
222
 
223
  if __name__ == "__main__":
224
  demo.launch(debug=True)