Update app.py
Browse files
app.py
CHANGED
@@ -4,27 +4,29 @@ import gradio as gr
|
|
4 |
import requests
|
5 |
import pandas as pd
|
6 |
|
7 |
-
from smolagents import CodeAgent, OpenAIServerModel
|
|
|
8 |
|
9 |
# Constants
|
10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
11 |
MAX_QUESTION_LENGTH = 4000
|
|
|
12 |
|
13 |
# Reliable search tool with retry
|
14 |
-
class
|
15 |
def run(self, query: str) -> str:
|
16 |
for attempt in range(3):
|
17 |
try:
|
18 |
return super().run(query)
|
19 |
except Exception as e:
|
20 |
if "rate" in str(e).lower():
|
21 |
-
print(f"[
|
22 |
time.sleep(2 * (attempt + 1))
|
23 |
else:
|
24 |
raise
|
25 |
-
raise RuntimeError("
|
26 |
|
27 |
-
# Main agent using GPT-4
|
28 |
class SmartGAIAAgent:
|
29 |
def __init__(self):
|
30 |
key = os.getenv("OPENAI_API_KEY")
|
@@ -32,7 +34,7 @@ class SmartGAIAAgent:
|
|
32 |
raise ValueError("Missing OPENAI_API_KEY")
|
33 |
model = OpenAIServerModel(model_id="gpt-4", api_key=key)
|
34 |
self.agent = CodeAgent(
|
35 |
-
tools=[
|
36 |
model=model,
|
37 |
add_base_tools=True
|
38 |
)
|
@@ -51,23 +53,25 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
51 |
if not username:
|
52 |
return "Please Login to Hugging Face", None
|
53 |
|
54 |
-
#
|
55 |
try:
|
56 |
agent = SmartGAIAAgent()
|
57 |
except Exception as e:
|
58 |
return f"Error initializing agent: {e}", None
|
59 |
|
60 |
-
#
|
61 |
resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
|
62 |
resp.raise_for_status()
|
63 |
questions = resp.json()
|
64 |
|
65 |
payload, logs = [], []
|
66 |
-
skip_kw = ['.mp3','.wav','.png','.jpg','youtube','video','watch','listen']
|
67 |
for item in questions:
|
68 |
tid = item.get("task_id")
|
69 |
-
q = item.get("question","")
|
70 |
-
if not tid or not q
|
|
|
|
|
71 |
continue
|
72 |
ans = agent(q)
|
73 |
payload.append({"task_id": tid, "submitted_answer": ans})
|
@@ -76,10 +80,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
76 |
if not payload:
|
77 |
return "No valid questions to submit.", pd.DataFrame(logs)
|
78 |
|
79 |
-
sub = {
|
|
|
|
|
|
|
|
|
80 |
resp = requests.post(f"{DEFAULT_API_URL}/submit", json=sub, timeout=60)
|
81 |
resp.raise_for_status()
|
82 |
result = resp.json()
|
|
|
83 |
status = f"Score: {result.get('score')}% ({result.get('correct_count')}/{result.get('total_attempted')})"
|
84 |
return status, pd.DataFrame(logs)
|
85 |
|
|
|
4 |
import requests
|
5 |
import pandas as pd
|
6 |
|
7 |
+
from smolagents import CodeAgent, OpenAIServerModel
|
8 |
+
from smolagents.tools import WebSearchTool # Correct tool
|
9 |
|
10 |
# Constants
|
11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
12 |
MAX_QUESTION_LENGTH = 4000
|
13 |
+
MAX_TOKENS_PER_QUESTION = 8000 # Safety margin to avoid 8192-token error
|
14 |
|
15 |
# Reliable search tool with retry
|
16 |
+
class ReliableWebSearchTool(WebSearchTool):
|
17 |
def run(self, query: str) -> str:
|
18 |
for attempt in range(3):
|
19 |
try:
|
20 |
return super().run(query)
|
21 |
except Exception as e:
|
22 |
if "rate" in str(e).lower():
|
23 |
+
print(f"[WebSearchTool] Rate limit, retry {attempt+1}/3")
|
24 |
time.sleep(2 * (attempt + 1))
|
25 |
else:
|
26 |
raise
|
27 |
+
raise RuntimeError("WebSearchTool failed after retries")
|
28 |
|
29 |
+
# Main agent using GPT-4 and tools
|
30 |
class SmartGAIAAgent:
|
31 |
def __init__(self):
|
32 |
key = os.getenv("OPENAI_API_KEY")
|
|
|
34 |
raise ValueError("Missing OPENAI_API_KEY")
|
35 |
model = OpenAIServerModel(model_id="gpt-4", api_key=key)
|
36 |
self.agent = CodeAgent(
|
37 |
+
tools=[ReliableWebSearchTool()],
|
38 |
model=model,
|
39 |
add_base_tools=True
|
40 |
)
|
|
|
53 |
if not username:
|
54 |
return "Please Login to Hugging Face", None
|
55 |
|
56 |
+
# Instantiate agent
|
57 |
try:
|
58 |
agent = SmartGAIAAgent()
|
59 |
except Exception as e:
|
60 |
return f"Error initializing agent: {e}", None
|
61 |
|
62 |
+
# Get questions
|
63 |
resp = requests.get(f"{DEFAULT_API_URL}/questions", timeout=15)
|
64 |
resp.raise_for_status()
|
65 |
questions = resp.json()
|
66 |
|
67 |
payload, logs = [], []
|
68 |
+
skip_kw = ['.mp3', '.wav', '.png', '.jpg', 'youtube', 'video', 'watch', 'listen']
|
69 |
for item in questions:
|
70 |
tid = item.get("task_id")
|
71 |
+
q = item.get("question", "")
|
72 |
+
if not tid or not q:
|
73 |
+
continue
|
74 |
+
if len(q) > MAX_QUESTION_LENGTH or any(k in q.lower() for k in skip_kw):
|
75 |
continue
|
76 |
ans = agent(q)
|
77 |
payload.append({"task_id": tid, "submitted_answer": ans})
|
|
|
80 |
if not payload:
|
81 |
return "No valid questions to submit.", pd.DataFrame(logs)
|
82 |
|
83 |
+
sub = {
|
84 |
+
"username": username,
|
85 |
+
"agent_code": f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main",
|
86 |
+
"answers": payload
|
87 |
+
}
|
88 |
resp = requests.post(f"{DEFAULT_API_URL}/submit", json=sub, timeout=60)
|
89 |
resp.raise_for_status()
|
90 |
result = resp.json()
|
91 |
+
|
92 |
status = f"Score: {result.get('score')}% ({result.get('correct_count')}/{result.get('total_attempted')})"
|
93 |
return status, pd.DataFrame(logs)
|
94 |
|