sirine1712 commited on
Commit
0696924
·
verified ·
1 Parent(s): ddef1f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -35
app.py CHANGED
@@ -2,22 +2,20 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
- from smolagents import ToolCallingAgent, tool
6
- from duckduckgo_search import DDGS
7
  import math
8
- from openai import OpenAI
9
 
10
- # Initialize OpenAI client
11
- client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
 
12
 
13
  # --- Tools ---
14
  @tool
15
  def web_search(query: str) -> str:
16
  """Performs a web search using DuckDuckGo.
17
-
18
  Args:
19
  query: The search query string.
20
-
21
  Returns:
22
  A formatted string with search results.
23
  """
@@ -34,27 +32,26 @@ def web_search(query: str) -> str:
34
  @tool
35
  def calculate(expression: str) -> str:
36
  """Evaluates mathematical expressions.
37
-
38
  Args:
39
  expression: The math expression to evaluate.
40
-
41
  Returns:
42
  The result as a string or error message.
43
  """
44
  try:
45
- safe_dict = {k: v for k, v in math.__dict__.items()
46
- if not k.startswith("__")}
47
  safe_dict.update({
48
  '__builtins__': None,
49
  'abs': abs,
50
  'round': round
51
  })
52
- result = eval(expression, {'__builtins__': None}, safe_dict)
53
  return str(result)
54
  except Exception as e:
55
  return f"Calculation error: {str(e)}"
56
 
57
- # --- Agent with Proper Initialization ---
58
  class GAIAAgent:
59
  def __init__(self):
60
  self.system_prompt = """You are an AI assistant that answers questions using tools:
@@ -63,13 +60,11 @@ class GAIAAgent:
63
  - Be concise and accurate"""
64
 
65
  try:
66
- # Initialize with proper configuration
67
  self.agent = ToolCallingAgent(
68
  name="GAIA_Agent",
69
  description=self.system_prompt,
70
  tools=[web_search, calculate],
71
- model=client, # Pass the OpenAI client directly
72
- model_kwargs={"model": "gpt-3.5-turbo"}, # Specify model here
73
  planning_interval=3
74
  )
75
  print("✅ Agent initialized successfully")
@@ -77,35 +72,30 @@ class GAIAAgent:
77
  raise RuntimeError(f"Agent init failed: {str(e)}")
78
 
79
  def __call__(self, question: str) -> str:
80
- """Process a question with proper error handling."""
81
  try:
82
  response = self.agent.run(question)
83
  return str(response) if response else "No answer generated"
84
  except Exception as e:
85
  return f"Error: {str(e)}"
86
 
87
-
88
- # --- Gradio Interface ---
89
  def submit_answers(profile: gr.OAuthProfile | None):
90
  if not profile:
91
  return "Please login to Hugging Face", None
92
 
93
  try:
94
  agent = GAIAAgent()
95
- response = requests.get(
96
- "https://agents-course-unit4-scoring.hf.space/questions",
97
- timeout=20
98
- )
99
  questions = response.json() or []
100
-
101
  answers = []
102
  results = []
103
-
104
- for item in questions[:15]:
105
  task_id = item.get("task_id", "")
106
  question = item.get("question", "")
107
  answer = agent(question)
108
-
109
  answers.append({
110
  "task_id": task_id,
111
  "submitted_answer": answer[:1000]
@@ -115,7 +105,7 @@ def submit_answers(profile: gr.OAuthProfile | None):
115
  "Question": question[:100],
116
  "Answer": answer[:200]
117
  })
118
-
119
  submit_response = requests.post(
120
  "https://agents-course-unit4-scoring.hf.space/submit",
121
  json={
@@ -126,24 +116,25 @@ def submit_answers(profile: gr.OAuthProfile | None):
126
  timeout=60
127
  )
128
  data = submit_response.json()
129
-
130
  return (
131
  f"Submitted {len(answers)} answers\n"
132
  f"Score: {data.get('score', 'N/A')}%\n"
133
  f"Correct: {data.get('correct_count', 0)}/{len(answers)}",
134
  pd.DataFrame(results)
135
  )
136
-
137
  except Exception as e:
138
  return f"Error: {str(e)}", None
139
 
 
140
  with gr.Blocks() as demo:
141
- gr.Markdown("# GAIA Agent")
142
  gr.LoginButton()
143
- submit_btn = gr.Button("Run Evaluation", variant="primary")
144
- output = gr.Textbox(label="Results")
145
- table = gr.DataFrame(label="Details")
146
- submit_btn.click(submit_answers, outputs=[output, table])
147
 
148
  if __name__ == "__main__":
149
  demo.launch()
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
 
 
5
  import math
 
6
 
7
+ from smolagents import ToolCallingAgent, tool
8
+ from instructor import OpenAIChat
9
+ from duckduckgo_search import DDGS
10
 
11
  # --- Tools ---
12
  @tool
13
  def web_search(query: str) -> str:
14
  """Performs a web search using DuckDuckGo.
15
+
16
  Args:
17
  query: The search query string.
18
+
19
  Returns:
20
  A formatted string with search results.
21
  """
 
32
  @tool
33
  def calculate(expression: str) -> str:
34
  """Evaluates mathematical expressions.
35
+
36
  Args:
37
  expression: The math expression to evaluate.
38
+
39
  Returns:
40
  The result as a string or error message.
41
  """
42
  try:
43
+ safe_dict = {k: v for k, v in math.__dict__.items() if not k.startswith("__")}
 
44
  safe_dict.update({
45
  '__builtins__': None,
46
  'abs': abs,
47
  'round': round
48
  })
49
+ result = eval(expression, {"__builtins__": None}, safe_dict)
50
  return str(result)
51
  except Exception as e:
52
  return f"Calculation error: {str(e)}"
53
 
54
+ # --- Agent ---
55
  class GAIAAgent:
56
  def __init__(self):
57
  self.system_prompt = """You are an AI assistant that answers questions using tools:
 
60
  - Be concise and accurate"""
61
 
62
  try:
 
63
  self.agent = ToolCallingAgent(
64
  name="GAIA_Agent",
65
  description=self.system_prompt,
66
  tools=[web_search, calculate],
67
+ model=OpenAIChat(model="gpt-3.5-turbo"), # Fixed model wrapper
 
68
  planning_interval=3
69
  )
70
  print("✅ Agent initialized successfully")
 
72
  raise RuntimeError(f"Agent init failed: {str(e)}")
73
 
74
  def __call__(self, question: str) -> str:
 
75
  try:
76
  response = self.agent.run(question)
77
  return str(response) if response else "No answer generated"
78
  except Exception as e:
79
  return f"Error: {str(e)}"
80
 
81
+ # --- Gradio Submission Logic ---
 
82
  def submit_answers(profile: gr.OAuthProfile | None):
83
  if not profile:
84
  return "Please login to Hugging Face", None
85
 
86
  try:
87
  agent = GAIAAgent()
88
+ response = requests.get("https://agents-course-unit4-scoring.hf.space/questions", timeout=20)
 
 
 
89
  questions = response.json() or []
90
+
91
  answers = []
92
  results = []
93
+
94
+ for item in questions[:15]: # Limit to 15 for speed
95
  task_id = item.get("task_id", "")
96
  question = item.get("question", "")
97
  answer = agent(question)
98
+
99
  answers.append({
100
  "task_id": task_id,
101
  "submitted_answer": answer[:1000]
 
105
  "Question": question[:100],
106
  "Answer": answer[:200]
107
  })
108
+
109
  submit_response = requests.post(
110
  "https://agents-course-unit4-scoring.hf.space/submit",
111
  json={
 
116
  timeout=60
117
  )
118
  data = submit_response.json()
119
+
120
  return (
121
  f"Submitted {len(answers)} answers\n"
122
  f"Score: {data.get('score', 'N/A')}%\n"
123
  f"Correct: {data.get('correct_count', 0)}/{len(answers)}",
124
  pd.DataFrame(results)
125
  )
126
+
127
  except Exception as e:
128
  return f"Error: {str(e)}", None
129
 
130
+ # --- Gradio Interface ---
131
  with gr.Blocks() as demo:
132
+ gr.Markdown("# GAIA Agent with DuckDuckGo + Calculator")
133
  gr.LoginButton()
134
+ btn = gr.Button("Run Evaluation", variant="primary")
135
+ status = gr.Textbox(label="Results")
136
+ df = gr.DataFrame(label="Evaluation Details")
137
+ btn.click(submit_answers, outputs=[status, df])
138
 
139
  if __name__ == "__main__":
140
  demo.launch()