mohdadrian commited on
Commit
977ec02
·
verified ·
1 Parent(s): eae379f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -29
app.py CHANGED
@@ -3,45 +3,88 @@ import time
3
  import requests
4
  import gradio as gr
5
  import pandas as pd
6
- from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, VisitWebpageTool
7
 
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  class BasicAgent:
12
  def __init__(self):
13
- print("Initializing HuggingFace agent...")
14
-
15
- self.model = InferenceClientModel(
16
- model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
17
  token=os.environ.get("HF_TOKEN"),
18
  )
19
-
20
- self.agent = CodeAgent(
21
- model=self.model,
22
- tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
23
- max_steps=3,
24
- verbosity_level=0,
25
- )
26
  print("✅ Ready")
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  def __call__(self, question: str, task_id: str = None) -> str:
29
  # Handle reversed text
30
- if '.rewsna' in question or 'tfel' in question:
31
  question = question[::-1]
 
32
 
33
- try:
34
- prompt = f"Answer in 1-5 words only: {question}"
35
- answer = str(self.agent.run(prompt)).strip()
36
-
37
- # Clean
38
- for p in ["Answer:", "The answer is", "Final answer:"]:
39
- if answer.lower().startswith(p.lower()):
40
- answer = answer[len(p):].strip()
41
- return answer.strip('."\'') or "unknown"
42
- except Exception as e:
43
- print(f"Error: {e}")
 
 
 
 
 
 
 
 
 
44
  return "unknown"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
 
47
  def run_and_submit_all(profile: gr.OAuthProfile | None):
@@ -51,7 +94,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
51
  username = profile.username
52
  space_id = os.getenv("SPACE_ID")
53
 
54
- print(f"\nUser: {username}")
55
 
56
  try:
57
  agent = BasicAgent()
@@ -73,11 +116,20 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
73
  question = q.get("question", "")
74
 
75
  print(f"[{i+1}] {question[:50]}...")
76
- answer = agent(question, task_id)
77
- print(f" → {answer[:50]}")
 
 
 
 
 
 
78
 
79
  answers.append({"task_id": task_id, "submitted_answer": answer})
80
  results.append({"#": i+1, "Q": question[:40]+"...", "A": answer[:50]})
 
 
 
81
 
82
  total = time.time() - start
83
  print(f"\n⏱️ {total:.0f}s")
@@ -85,7 +137,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
85
  try:
86
  result = requests.post(
87
  f"{DEFAULT_API_URL}/submit",
88
- json={"username": username, "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main", "answers": answers},
 
 
 
 
89
  timeout=60
90
  ).json()
91
 
@@ -101,7 +157,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
101
 
102
 
103
  with gr.Blocks() as demo:
104
- gr.Markdown("# 🎯 GAIA Agent - HuggingFace")
 
105
  gr.LoginButton()
106
  btn = gr.Button("🚀 Run", variant="primary")
107
  status = gr.Textbox(label="Status", lines=5)
 
3
  import requests
4
  import gradio as gr
5
  import pandas as pd
6
+ from huggingface_hub import InferenceClient
7
 
8
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
9
 
10
 
11
+ def web_search(query: str) -> str:
12
+ """Search using DuckDuckGo"""
13
+ try:
14
+ from duckduckgo_search import DDGS
15
+ with DDGS() as ddgs:
16
+ results = list(ddgs.text(query, max_results=3))
17
+ if results:
18
+ return "\n".join([f"- {r['title']}: {r['body']}" for r in results])
19
+ except:
20
+ pass
21
+ return ""
22
+
23
+
24
  class BasicAgent:
25
  def __init__(self):
26
+ print("Initializing agent...")
27
+ self.client = InferenceClient(
28
+ model="Qwen/Qwen2.5-72B-Instruct",
 
29
  token=os.environ.get("HF_TOKEN"),
30
  )
 
 
 
 
 
 
 
31
  print("✅ Ready")
32
 
33
+ def ask(self, prompt: str) -> str:
34
+ """Simple LLM call"""
35
+ try:
36
+ response = self.client.chat_completion(
37
+ messages=[{"role": "user", "content": prompt}],
38
+ max_tokens=50,
39
+ temperature=0.1,
40
+ )
41
+ return response.choices[0].message.content.strip()
42
+ except Exception as e:
43
+ print(f" LLM error: {e}")
44
+ return ""
45
+
46
  def __call__(self, question: str, task_id: str = None) -> str:
47
  # Handle reversed text
48
+ if '.rewsna' in question or 'tfel' in question or 'eht fo' in question:
49
  question = question[::-1]
50
+ print(f" [Reversed → {question[:50]}...]")
51
 
52
+ # Search for context
53
+ search_results = web_search(question[:100])
54
+
55
+ # Build simple prompt
56
+ context = f"Search results:\n{search_results}\n\n" if search_results else ""
57
+
58
+ prompt = f"""{context}Question: {question}
59
+
60
+ Answer with ONLY the final answer.
61
+ - If it's a number, just the number (e.g., "42")
62
+ - If it's a name, just the name (e.g., "John Smith")
63
+ - If it's a list, comma-separated (e.g., "apple, banana, cherry")
64
+ - Maximum 5 words
65
+
66
+ Answer:"""
67
+
68
+ answer = self.ask(prompt)
69
+
70
+ # Clean the answer
71
+ if not answer:
72
  return "unknown"
73
+
74
+ # Remove common prefixes
75
+ for prefix in ["Answer:", "The answer is:", "The answer is", "A:", "Final answer:"]:
76
+ if answer.lower().startswith(prefix.lower()):
77
+ answer = answer[len(prefix):].strip()
78
+
79
+ # Remove quotes and periods
80
+ answer = answer.strip('."\'')
81
+
82
+ # If answer is too long or contains excuses, retry with simpler prompt
83
+ if len(answer) > 100 or any(x in answer.lower() for x in ["i cannot", "i don't", "unable"]):
84
+ answer = self.ask(f"In 1-3 words, answer: {question}")
85
+ answer = answer.strip('."\'')
86
+
87
+ return answer if answer else "unknown"
88
 
89
 
90
  def run_and_submit_all(profile: gr.OAuthProfile | None):
 
94
  username = profile.username
95
  space_id = os.getenv("SPACE_ID")
96
 
97
+ print(f"\n{'='*40}\nUser: {username}\n{'='*40}")
98
 
99
  try:
100
  agent = BasicAgent()
 
116
  question = q.get("question", "")
117
 
118
  print(f"[{i+1}] {question[:50]}...")
119
+
120
+ try:
121
+ answer = agent(question, task_id)
122
+ except Exception as e:
123
+ print(f" Error: {e}")
124
+ answer = "unknown"
125
+
126
+ print(f" → {answer}")
127
 
128
  answers.append({"task_id": task_id, "submitted_answer": answer})
129
  results.append({"#": i+1, "Q": question[:40]+"...", "A": answer[:50]})
130
+
131
+ # Small delay to avoid rate limits
132
+ time.sleep(1)
133
 
134
  total = time.time() - start
135
  print(f"\n⏱️ {total:.0f}s")
 
137
  try:
138
  result = requests.post(
139
  f"{DEFAULT_API_URL}/submit",
140
+ json={
141
+ "username": username,
142
+ "agent_code": f"https://huggingface.co/spaces/{space_id}/tree/main",
143
+ "answers": answers
144
+ },
145
  timeout=60
146
  ).json()
147
 
 
157
 
158
 
159
  with gr.Blocks() as demo:
160
+ gr.Markdown("# 🎯 GAIA Agent - Simple Mode")
161
+ gr.Markdown("Direct search + LLM (no code execution)")
162
  gr.LoginButton()
163
  btn = gr.Button("🚀 Run", variant="primary")
164
  status = gr.Textbox(label="Status", lines=5)