sirine1712 commited on
Commit
326bc46
Β·
verified Β·
1 Parent(s): 43ab812

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -41
app.py CHANGED
@@ -5,9 +5,7 @@ import pandas as pd
5
  from smolagents import ToolCallingAgent, tool
6
  from duckduckgo_search import DDGS
7
  import math
8
-
9
- # --- Constants ---
10
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
  # --- Tools ---
13
  @tool
@@ -22,24 +20,23 @@ def duck_search(query: str) -> str:
22
  A string summarizing the top search results.
23
  """
24
  try:
25
- results = ddg(query, max_results=3)
26
- if results:
27
- return "\n\n".join([f"{r['title']}: {r['body']}" for r in results])
28
- else:
29
- return "No results found."
30
  except Exception as e:
31
  return f"Search error: {e}"
32
 
33
  @tool
34
  def calculator(expression: str) -> str:
35
  """
36
- Safely evaluates math expressions using Python's math module.
37
 
38
  Args:
39
- expression: A valid math expression as a string (e.g., 'sqrt(16) + 10').
40
 
41
  Returns:
42
- The result of the evaluated expression or an error message.
43
  """
44
  try:
45
  result = eval(expression, {"__builtins__": {}}, math.__dict__)
@@ -52,12 +49,13 @@ class WebSearchAgent:
52
  def __init__(self):
53
  self.agent = ToolCallingAgent(
54
  name="GAIAWebToolAgent",
55
- description="Agent that answers questions using web search and calculator tools.",
56
  tools=[duck_search, calculator],
 
57
  step_limit=5,
58
  system_prompt=(
59
- "You're a helpful reasoning agent. Use available tools like web search "
60
- "and calculator to answer the user's question accurately and concisely."
61
  ),
62
  )
63
  print("βœ… Agent initialized.")
@@ -70,7 +68,10 @@ class WebSearchAgent:
70
  print(f"❌ Agent error: {e}")
71
  return f"Error: {e}"
72
 
73
- # --- Evaluation and Submission ---
 
 
 
74
  def run_and_submit_all(profile: gr.OAuthProfile | None):
75
  space_id = os.getenv("SPACE_ID")
76
  if profile:
@@ -89,13 +90,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
89
  return f"Agent initialization error: {e}", None
90
 
91
  try:
92
- print("πŸ“₯ Fetching questions...")
93
  response = requests.get(questions_url, timeout=15)
94
  response.raise_for_status()
95
  questions = response.json()
96
  if not questions:
97
  return "No questions received.", None
98
- print(f"βœ… Retrieved {len(questions)} questions.")
99
  except Exception as e:
100
  return f"Failed to fetch questions: {e}", None
101
 
@@ -109,27 +108,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
109
  continue
110
  try:
111
  answer = agent(question)
112
- results_log.append({
113
- "Task ID": task_id,
114
- "Question": question,
115
- "Submitted Answer": answer
116
- })
117
- answers_payload.append({
118
- "task_id": task_id,
119
- "submitted_answer": answer
120
- })
121
  except Exception as e:
122
  error_msg = f"Agent error: {e}"
123
- results_log.append({
124
- "Task ID": task_id,
125
- "Question": question,
126
- "Submitted Answer": error_msg
127
- })
128
 
129
  if not answers_payload:
130
  return "No answers were generated.", pd.DataFrame(results_log)
131
 
132
- print("πŸ“€ Submitting answers...")
133
  try:
134
  response = requests.post(submit_url, json={
135
  "username": username.strip(),
@@ -149,14 +136,9 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
149
  except Exception as e:
150
  return f"❌ Submission failed: {e}", pd.DataFrame(results_log)
151
 
152
- # --- Gradio UI ---
153
  with gr.Blocks() as demo:
154
- gr.Markdown("# πŸ€– GAIA Agent with Web Search & Calculator Tools")
155
- gr.Markdown("""
156
- - βœ… Log in to your Hugging Face account
157
- - πŸš€ Click the button to run and submit your agent
158
- - 🧠 Agent uses DuckDuckGo search + calculator
159
- """)
160
  gr.LoginButton()
161
  run_btn = gr.Button("Run Evaluation & Submit All Answers")
162
  status_box = gr.Textbox(label="Status", lines=5)
@@ -165,5 +147,4 @@ with gr.Blocks() as demo:
165
  run_btn.click(fn=run_and_submit_all, outputs=[status_box, result_table])
166
 
167
  if __name__ == "__main__":
168
- print("πŸš€ Starting Gradio App...")
169
- demo.launch(debug=True, share=False)
 
5
  from smolagents import ToolCallingAgent, tool
6
  from duckduckgo_search import DDGS
7
  import math
8
+ import openai
 
 
9
 
10
  # --- Tools ---
11
  @tool
 
20
  A string summarizing the top search results.
21
  """
22
  try:
23
+ with DDGS() as ddgs:
24
+ results = ddgs.text(query, max_results=3)
25
+ summaries = [f"{r['title']}: {r['body']}" for r in results]
26
+ return "\n\n".join(summaries) if summaries else "No results found."
 
27
  except Exception as e:
28
  return f"Search error: {e}"
29
 
30
  @tool
31
  def calculator(expression: str) -> str:
32
  """
33
+ Evaluates basic math expressions using math module.
34
 
35
  Args:
36
+ expression: A math expression as a string.
37
 
38
  Returns:
39
+ The result or an error message.
40
  """
41
  try:
42
  result = eval(expression, {"__builtins__": {}}, math.__dict__)
 
49
  def __init__(self):
50
  self.agent = ToolCallingAgent(
51
  name="GAIAWebToolAgent",
52
+ description="An agent using DuckDuckGo and calculator tools.",
53
  tools=[duck_search, calculator],
54
+ model="gpt-3.5-turbo", # You can use gpt-4o if you have access
55
  step_limit=5,
56
  system_prompt=(
57
+ "You're a helpful reasoning agent. Use the provided tools "
58
+ "to help answer the user's questions accurately."
59
  ),
60
  )
61
  print("βœ… Agent initialized.")
 
68
  print(f"❌ Agent error: {e}")
69
  return f"Error: {e}"
70
 
71
+ # --- Constants ---
72
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
73
+
74
+ # --- Evaluation & Submission ---
75
  def run_and_submit_all(profile: gr.OAuthProfile | None):
76
  space_id = os.getenv("SPACE_ID")
77
  if profile:
 
90
  return f"Agent initialization error: {e}", None
91
 
92
  try:
 
93
  response = requests.get(questions_url, timeout=15)
94
  response.raise_for_status()
95
  questions = response.json()
96
  if not questions:
97
  return "No questions received.", None
 
98
  except Exception as e:
99
  return f"Failed to fetch questions: {e}", None
100
 
 
108
  continue
109
  try:
110
  answer = agent(question)
111
+ results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": answer})
112
+ answers_payload.append({"task_id": task_id, "submitted_answer": answer})
 
 
 
 
 
 
 
113
  except Exception as e:
114
  error_msg = f"Agent error: {e}"
115
+ results_log.append({"Task ID": task_id, "Question": question, "Submitted Answer": error_msg})
 
 
 
 
116
 
117
  if not answers_payload:
118
  return "No answers were generated.", pd.DataFrame(results_log)
119
 
 
120
  try:
121
  response = requests.post(submit_url, json={
122
  "username": username.strip(),
 
136
  except Exception as e:
137
  return f"❌ Submission failed: {e}", pd.DataFrame(results_log)
138
 
139
+ # --- UI ---
140
  with gr.Blocks() as demo:
141
+ gr.Markdown("# πŸ€– GAIA Agent with Web Search & Calculator")
 
 
 
 
 
142
  gr.LoginButton()
143
  run_btn = gr.Button("Run Evaluation & Submit All Answers")
144
  status_box = gr.Textbox(label="Status", lines=5)
 
147
  run_btn.click(fn=run_and_submit_all, outputs=[status_box, result_table])
148
 
149
  if __name__ == "__main__":
150
+ demo.launch(debug=True, share=False)