Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
|
| 10 |
|
| 11 |
-
class
|
|
|
|
| 12 |
def __init__(self):
|
| 13 |
-
|
| 14 |
-
|
| 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(
|
| 27 |
-
|
| 28 |
def __call__(self, question: str) -> str:
|
| 29 |
-
"""
|
| 30 |
if self.agent is None:
|
| 31 |
-
return "
|
| 32 |
|
| 33 |
try:
|
| 34 |
-
headers = {
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
payload = {
|
| 37 |
-
"
|
| 38 |
-
"
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
}
|
| 42 |
|
| 43 |
response = requests.post(
|
| 44 |
-
|
| 45 |
headers=headers,
|
| 46 |
json=payload,
|
| 47 |
-
timeout=
|
| 48 |
)
|
| 49 |
|
| 50 |
-
if response.status_code == 410:
|
| 51 |
-
return "Model loading... please try again"
|
| 52 |
-
|
| 53 |
if response.status_code != 200:
|
| 54 |
-
|
|
|
|
| 55 |
|
| 56 |
result = response.json()
|
|
|
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 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)[:
|
| 67 |
|
| 68 |
|
| 69 |
def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
| 70 |
"""ไธป่ฆ่ฉไผฐๅๆไบคๅฝๆธ"""
|
| 71 |
|
|
|
|
| 72 |
if profile is None:
|
| 73 |
-
return "Please Login
|
| 74 |
|
| 75 |
username = profile.username
|
| 76 |
space_id = os.getenv("SPACE_ID", "s1144662")
|
| 77 |
-
|
| 78 |
api_url = DEFAULT_API_URL
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
try:
|
| 83 |
-
agent =
|
|
|
|
|
|
|
| 84 |
except Exception as e:
|
| 85 |
-
return f"
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
try:
|
| 90 |
-
|
|
|
|
| 91 |
response.raise_for_status()
|
| 92 |
questions_data = response.json()
|
|
|
|
| 93 |
except Exception as e:
|
| 94 |
-
return f"
|
| 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 |
-
|
|
|
|
| 108 |
answers_payload.append({
|
| 109 |
-
"task_id": task_id,
|
| 110 |
-
"submitted_answer":
|
| 111 |
})
|
|
|
|
| 112 |
results_log.append({
|
| 113 |
-
"Task ID": task_id
|
| 114 |
-
"Question": question_text[:
|
| 115 |
-
"Answer":
|
| 116 |
})
|
|
|
|
| 117 |
except Exception as e:
|
|
|
|
| 118 |
answers_payload.append({
|
| 119 |
-
"task_id": task_id,
|
| 120 |
-
"submitted_answer":
|
| 121 |
})
|
| 122 |
results_log.append({
|
| 123 |
-
"Task ID": task_id
|
| 124 |
-
"Question": question_text[:
|
| 125 |
-
"Answer":
|
| 126 |
})
|
| 127 |
|
| 128 |
-
|
| 129 |
-
"username": username,
|
| 130 |
-
"agent_code": agent_code,
|
| 131 |
-
"answers": answers_payload
|
| 132 |
-
}
|
| 133 |
-
|
| 134 |
try:
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
response.raise_for_status()
|
| 137 |
-
|
| 138 |
|
| 139 |
-
score =
|
| 140 |
-
correct =
|
| 141 |
-
total_q =
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
except Exception as e:
|
| 144 |
-
status_msg = f"
|
| 145 |
|
| 146 |
return status_msg, pd.DataFrame(results_log)
|
| 147 |
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
with gr.Row():
|
| 154 |
gr.LoginButton(scale=1)
|
| 155 |
-
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
| 161 |
fn=run_and_submit_all,
|
| 162 |
inputs=[],
|
| 163 |
-
outputs=[
|
| 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)
|