Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,77 +3,60 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 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
|
| 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
|
| 16 |
self.agent = None
|
| 17 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def __call__(self, question: str) -> str:
|
| 23 |
"""回答問題"""
|
| 24 |
if self.agent is None:
|
| 25 |
-
return "Error: GROQ_API_KEY not configured.
|
| 26 |
|
| 27 |
try:
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
{
|
| 37 |
-
"role": "system",
|
| 38 |
-
"content": (
|
| 39 |
-
"You are taking a strict multiple-choice exam. "
|
| 40 |
-
"For each question, give ONLY the final answer in 1-2 sentences. "
|
| 41 |
-
"No explanations, no introductions, no 'I'm an AI' statements. "
|
| 42 |
-
"If you can't see a video/image/file, use web knowledge and typical context to infer."
|
| 43 |
-
)
|
| 44 |
-
},
|
| 45 |
-
{
|
| 46 |
-
"role": "user",
|
| 47 |
-
"content": f"Question: {question}\n\nAnswer:"
|
| 48 |
-
}
|
| 49 |
-
],
|
| 50 |
-
"temperature": 0.1, # 更低的隨機性
|
| 51 |
-
"max_tokens": 300,
|
| 52 |
-
"top_p": 0.9
|
| 53 |
-
}
|
| 54 |
-
response = requests.post(
|
| 55 |
-
GROQ_API_URL,
|
| 56 |
-
headers=headers,
|
| 57 |
-
json=payload,
|
| 58 |
-
timeout=30
|
| 59 |
-
)
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
return f"API Error {response.status_code}: {error_msg}"
|
| 64 |
|
| 65 |
-
|
| 66 |
-
answer =
|
|
|
|
| 67 |
|
| 68 |
-
# 限制答案長度
|
| 69 |
-
return answer[:1000] if answer else "Unable to generate answer"
|
| 70 |
-
|
| 71 |
-
except requests.exceptions.Timeout:
|
| 72 |
-
return "Request timeout - please try again"
|
| 73 |
-
except requests.exceptions.RequestException as e:
|
| 74 |
-
return f"Network error: {str(e)[:100]}"
|
| 75 |
except Exception as e:
|
| 76 |
-
return f"Error: {str(e)[:150]}"
|
| 77 |
|
| 78 |
|
| 79 |
def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
@@ -89,9 +72,9 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 89 |
|
| 90 |
# 初始化 Agent
|
| 91 |
try:
|
| 92 |
-
|
| 93 |
-
if
|
| 94 |
-
return "❌ Error: GROQ_API_KEY not found!\n\nPlease add your Groq API key to Secrets
|
| 95 |
except Exception as e:
|
| 96 |
return f"❌ Agent initialization failed: {str(e)}", None
|
| 97 |
|
|
@@ -118,7 +101,8 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 118 |
print(f"[{idx}/{total}] Processing: {task_id[:8]}...")
|
| 119 |
|
| 120 |
try:
|
| 121 |
-
|
|
|
|
| 122 |
|
| 123 |
answers_payload.append({
|
| 124 |
"task_id": task_id,
|
|
@@ -128,7 +112,7 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 128 |
results_log.append({
|
| 129 |
"Task ID": task_id[:12] + "...",
|
| 130 |
"Question": question_text[:70] + "...",
|
| 131 |
-
"Answer": answer[:150]
|
| 132 |
})
|
| 133 |
|
| 134 |
except Exception as e:
|
|
@@ -138,8 +122,8 @@ def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
| 138 |
"submitted_answer": f"Error: {error_msg}"
|
| 139 |
})
|
| 140 |
results_log.append({
|
| 141 |
-
"Task ID": task_id
|
| 142 |
-
"Question": question_text[:
|
| 143 |
"Answer": f"Error: {error_msg}"
|
| 144 |
})
|
| 145 |
|
|
@@ -182,7 +166,7 @@ Great job! 🚀"""
|
|
| 182 |
❌ Required: 30% to pass
|
| 183 |
📈 You need {int((30 * total_q / 100) - correct)} more correct answers
|
| 184 |
|
| 185 |
-
💡
|
| 186 |
|
| 187 |
except requests.exceptions.RequestException as e:
|
| 188 |
status_msg = f"❌ Submission failed (network error): {str(e)[:200]}"
|
|
@@ -195,9 +179,9 @@ Great job! 🚀"""
|
|
| 195 |
# Gradio 介面
|
| 196 |
with gr.Blocks(title="Unit 4 Final Assignment", theme=gr.themes.Soft()) as demo:
|
| 197 |
gr.Markdown("""
|
| 198 |
-
# 🎓 Unit 4 Final Project: AI Agent
|
| 199 |
|
| 200 |
-
### Using Groq API (Llama 3.3 70B)
|
| 201 |
**Goal**: Score ≥ 30% to get certificate
|
| 202 |
""")
|
| 203 |
|
|
@@ -219,10 +203,10 @@ with gr.Blocks(title="Unit 4 Final Assignment", theme=gr.themes.Soft()) as demo:
|
|
| 219 |
gr.Markdown("""
|
| 220 |
---
|
| 221 |
### 💡 Tips
|
| 222 |
-
- Make sure
|
| 223 |
-
-
|
| 224 |
-
-
|
| 225 |
""")
|
| 226 |
|
| 227 |
if __name__ == "__main__":
|
| 228 |
-
demo.launch(
|
|
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
from typing import Optional
|
| 6 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel
|
| 7 |
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 9 |
|
| 10 |
class GroqAgent:
|
| 11 |
+
"""使用 smolagents + Groq API + Search Tool 的 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")
|
| 16 |
self.agent = None
|
| 17 |
return
|
| 18 |
+
|
| 19 |
+
# 1. 設定模型:使用 OpenAI 相容模式連接 Groq
|
| 20 |
+
model = OpenAIServerModel(
|
| 21 |
+
model_id="llama-3.3-70b-versatile",
|
| 22 |
+
api_base="https://api.groq.com/openai/v1",
|
| 23 |
+
api_key=self.api_key
|
| 24 |
+
)
|
| 25 |
|
| 26 |
+
# 2. 建立 Agent:加入搜尋工具 (DuckDuckGoSearchTool)
|
| 27 |
+
# 這是拿到 > 30% 分數的關鍵,讓它能上網查資料
|
| 28 |
+
self.agent = CodeAgent(
|
| 29 |
+
tools=[DuckDuckGoSearchTool()],
|
| 30 |
+
model=model,
|
| 31 |
+
max_steps=4, # 限制思考步數避免超時
|
| 32 |
+
verbosity_level=1
|
| 33 |
+
)
|
| 34 |
+
print("✓ Groq agent (smolagents) initialized successfully")
|
| 35 |
|
| 36 |
def __call__(self, question: str) -> str:
|
| 37 |
"""回答問題"""
|
| 38 |
if self.agent is None:
|
| 39 |
+
return "Error: GROQ_API_KEY not configured."
|
| 40 |
|
| 41 |
try:
|
| 42 |
+
# 增加提示詞,告訴 Agent 如果遇到圖片題該怎麼辦
|
| 43 |
+
prompt = f"""
|
| 44 |
+
Answer the following question as strictly and concisely as possible.
|
| 45 |
+
If the question asks about a specific fact, use the search tool to find it.
|
| 46 |
+
If the question refers to an image, video, or audio file that you cannot see:
|
| 47 |
+
1. Try to infer the answer from the text context if possible.
|
| 48 |
+
2. Or search for the specific text descriptions in the question.
|
| 49 |
+
3. If absolutely impossible, make an educated guess.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
Question: {question}
|
| 52 |
+
"""
|
|
|
|
| 53 |
|
| 54 |
+
# 執行 Agent
|
| 55 |
+
answer = self.agent.run(prompt)
|
| 56 |
+
return str(answer)
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
except Exception as e:
|
| 59 |
+
return f"Error running agent: {str(e)[:150]}"
|
| 60 |
|
| 61 |
|
| 62 |
def run_and_submit_all(profile: Optional[gr.OAuthProfile] = None):
|
|
|
|
| 72 |
|
| 73 |
# 初始化 Agent
|
| 74 |
try:
|
| 75 |
+
agent_wrapper = GroqAgent()
|
| 76 |
+
if agent_wrapper.agent is None:
|
| 77 |
+
return "❌ Error: GROQ_API_KEY not found!\n\nPlease add your Groq API key to Secrets.", None
|
| 78 |
except Exception as e:
|
| 79 |
return f"❌ Agent initialization failed: {str(e)}", None
|
| 80 |
|
|
|
|
| 101 |
print(f"[{idx}/{total}] Processing: {task_id[:8]}...")
|
| 102 |
|
| 103 |
try:
|
| 104 |
+
# 呼叫我們的 Agent
|
| 105 |
+
answer = agent_wrapper(question_text)
|
| 106 |
|
| 107 |
answers_payload.append({
|
| 108 |
"task_id": task_id,
|
|
|
|
| 112 |
results_log.append({
|
| 113 |
"Task ID": task_id[:12] + "...",
|
| 114 |
"Question": question_text[:70] + "...",
|
| 115 |
+
"Answer": str(answer)[:150]
|
| 116 |
})
|
| 117 |
|
| 118 |
except Exception as e:
|
|
|
|
| 122 |
"submitted_answer": f"Error: {error_msg}"
|
| 123 |
})
|
| 124 |
results_log.append({
|
| 125 |
+
"Task ID": task_id,
|
| 126 |
+
"Question": question_text[:50],
|
| 127 |
"Answer": f"Error: {error_msg}"
|
| 128 |
})
|
| 129 |
|
|
|
|
| 166 |
❌ Required: 30% to pass
|
| 167 |
📈 You need {int((30 * total_q / 100) - correct)} more correct answers
|
| 168 |
|
| 169 |
+
💡 Tip: Check if the search tool is working correctly."""
|
| 170 |
|
| 171 |
except requests.exceptions.RequestException as e:
|
| 172 |
status_msg = f"❌ Submission failed (network error): {str(e)[:200]}"
|
|
|
|
| 179 |
# Gradio 介面
|
| 180 |
with gr.Blocks(title="Unit 4 Final Assignment", theme=gr.themes.Soft()) as demo:
|
| 181 |
gr.Markdown("""
|
| 182 |
+
# 🎓 Unit 4 Final Project: AI Agent (Fixed with smolagents)
|
| 183 |
|
| 184 |
+
### Using Groq API (Llama 3.3 70B) + Search Tool
|
| 185 |
**Goal**: Score ≥ 30% to get certificate
|
| 186 |
""")
|
| 187 |
|
|
|
|
| 203 |
gr.Markdown("""
|
| 204 |
---
|
| 205 |
### 💡 Tips
|
| 206 |
+
- Make sure `GROQ_API_KEY` is in Secrets.
|
| 207 |
+
- This agent uses DuckDuckGo Search to answer factual questions.
|
| 208 |
+
- Image questions might still fail, but text questions should pass!
|
| 209 |
""")
|
| 210 |
|
| 211 |
if __name__ == "__main__":
|
| 212 |
+
demo.launch()
|