Snaseem2026 commited on
Commit
9595eda
·
verified ·
1 Parent(s): c00ddde

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -58
app.py CHANGED
@@ -3,45 +3,62 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
6
- from smolagents import CodeAgent, HfApiModel
7
 
8
  # --- Constants ---
9
- DEFAULT_API_URL = "https://agents-course-unit4-scoring. hf.space"
10
 
11
- # --- Agent Definition ---
12
- class BasicAgent:
13
  def __init__(self):
14
  print("BasicAgent initialized.")
15
- # Initialize the model and agent here
16
  try:
 
17
  model = HfApiModel()
18
- self.agent = CodeAgent(tools=[], model=model, max_steps=4)
19
- except Exception as e:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  print(f"Error initializing agent: {e}")
21
  self.agent = None
22
 
23
  def __call__(self, question: str) -> str:
24
  print(f"Agent received question (first 50 chars): {question[:50]}...")
25
 
26
- if self.agent is None:
27
  return "Agent failed to initialize properly."
28
 
29
  try:
30
  # Run the agent with the question
31
- answer = self.agent. run(question)
32
- print(f"Agent returning answer: {str(answer)[:100]}...")
33
- return str(answer)
 
34
  except Exception as e:
35
- print(f"Error running agent: {e}")
36
- return f"Error processing question: {str(e)}"
 
37
 
38
  def run_and_submit_all(profile: gr.OAuthProfile | None):
39
  """
40
  Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results.
41
  """
42
- space_id = os.getenv("SPACE_ID")
 
43
  if profile:
44
- username = f"{profile.username}"
45
  print(f"User logged in: {username}")
46
  else:
47
  print("User not logged in.")
@@ -52,17 +69,18 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
52
  submit_url = f"{api_url}/submit"
53
 
54
  # 1. Instantiate Agent
55
- try:
56
  agent = BasicAgent()
57
- except Exception as e:
58
  print(f"Error instantiating agent: {e}")
59
  return f"Error initializing agent: {e}", None
60
 
 
61
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
62
  print(f"Agent code URL: {agent_code}")
63
 
64
  # 2. Fetch Questions
65
- print(f"Fetching questions from: {questions_url}")
66
  try:
67
  response = requests.get(questions_url, timeout=30)
68
  response.raise_for_status()
@@ -76,8 +94,8 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
76
  return f"Error fetching questions: {e}", None
77
  except requests.exceptions.JSONDecodeError as e:
78
  print(f"Error decoding JSON response from questions endpoint: {e}")
79
- print(f"Response text: {response.text[: 500]}")
80
- return f"Error decoding server response for questions: {e}", None
81
  except Exception as e:
82
  print(f"An unexpected error occurred fetching questions: {e}")
83
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -86,65 +104,86 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
86
  results_log = []
87
  answers_payload = []
88
  print(f"Running agent on {len(questions_data)} questions...")
89
-
90
- for item in questions_data:
91
- task_id = item. get("task_id")
92
  question_text = item.get("question")
93
- if not task_id or question_text is None:
94
- print(f"Skipping item with missing task_id or question: {item}")
95
  continue
96
 
97
  try:
98
  answer = agent(question_text)
99
  answers_payload.append({"task_id": task_id, "answer": answer})
100
- results_log.append({"task_id": task_id, "question": question_text[: 50], "answer": str(answer)[:100]})
 
 
 
 
101
  except Exception as e:
102
  print(f"Error processing task {task_id}: {e}")
103
  answers_payload.append({"task_id": task_id, "answer": f"Error: {str(e)}"})
104
 
105
  # 4. Submit answers
106
- print(f"Submitting {len(answers_payload)} answers...")
107
  try:
108
- payload = {
109
- "username": username,
110
- "agent_code": agent_code,
111
- "answers": answers_payload
112
- }
113
-
114
- response = requests.post(submit_url, json=payload, timeout=30)
115
- response.raise_for_status()
116
- result = response.json()
117
-
118
- print(f"Submission successful: {result}")
119
-
120
- # Create results dataframe
121
- df = pd.DataFrame(results_log)
122
-
123
- return f"✅ Submission successful! Score: {result. get('score', 'N/A')}", df
124
-
125
  except requests.exceptions.RequestException as e:
126
  print(f"Error submitting answers: {e}")
127
  return f"Error submitting answers: {e}", pd.DataFrame(results_log)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  except Exception as e:
129
- print(f"Unexpected error during submission: {e}")
130
- return f"Unexpected error during submission: {e}", pd.DataFrame(results_log)
 
 
 
 
131
 
132
- # --- Gradio Interface ---
133
  with gr.Blocks() as demo:
134
- gr.Markdown("# 🤖 Agent Assignment Submission")
135
- gr.Markdown("Click the button below to run your agent on all questions and submit your answers.")
136
 
137
  with gr.Row():
138
- submit_btn = gr.Button("🚀 Run & Submit All", variant="primary")
139
 
140
- status_output = gr.Textbox(label="Status", lines=3)
141
- results_output = gr. Dataframe(label="Results")
142
 
143
- submit_btn. click(
144
- fn=run_and_submit_all,
145
- inputs=[],
146
- outputs=[status_output, results_output]
 
 
 
 
 
 
 
147
  )
148
 
149
- if __name__ == "__main__":
150
- demo.launch()
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, VisitWebpageTool
7
 
8
  # --- Constants ---
9
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
+ # --- Intelligent Agent Definition ---
12
+ class BasicAgent:
13
  def __init__(self):
14
  print("BasicAgent initialized.")
 
15
  try:
16
+ # Initialize the model
17
  model = HfApiModel()
18
+
19
+ # Initialize tools for the agent
20
+ tools = [
21
+ DuckDuckGoSearchTool(),
22
+ VisitWebpageTool()
23
+ ]
24
+
25
+ # Create the CodeAgent with tools
26
+ self.agent = CodeAgent(
27
+ tools=tools,
28
+ model=model,
29
+ max_steps=10,
30
+ verbosity_level=2
31
+ )
32
+ print("Agent successfully initialized with tools.")
33
+ except Exception as e:
34
  print(f"Error initializing agent: {e}")
35
  self.agent = None
36
 
37
  def __call__(self, question: str) -> str:
38
  print(f"Agent received question (first 50 chars): {question[:50]}...")
39
 
40
+ if self. agent is None:
41
  return "Agent failed to initialize properly."
42
 
43
  try:
44
  # Run the agent with the question
45
+ result = self. agent.run(question)
46
+ answer = str(result)
47
+ print(f"Agent returning answer (first 100 chars): {answer[:100]}...")
48
+ return answer
49
  except Exception as e:
50
+ print(f"Error running agent on question: {e}")
51
+ # Return a fallback answer
52
+ return f"I encountered an error: {str(e)}"
53
 
54
  def run_and_submit_all(profile: gr.OAuthProfile | None):
55
  """
56
  Fetches all questions, runs the BasicAgent on them, submits all answers, and displays the results.
57
  """
58
+ # --- Determine HF Space Runtime URL and Repo URL ---
59
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
60
  if profile:
61
+ username = f"{profile. username}"
62
  print(f"User logged in: {username}")
63
  else:
64
  print("User not logged in.")
 
69
  submit_url = f"{api_url}/submit"
70
 
71
  # 1. Instantiate Agent
72
+ try:
73
  agent = BasicAgent()
74
+ except Exception as e:
75
  print(f"Error instantiating agent: {e}")
76
  return f"Error initializing agent: {e}", None
77
 
78
+ # In the case of an app running as a Hugging Face Space, this link points toward your codebase
79
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
80
  print(f"Agent code URL: {agent_code}")
81
 
82
  # 2. Fetch Questions
83
+ print(f"Fetching questions from: {questions_url}")
84
  try:
85
  response = requests.get(questions_url, timeout=30)
86
  response.raise_for_status()
 
94
  return f"Error fetching questions: {e}", None
95
  except requests.exceptions.JSONDecodeError as e:
96
  print(f"Error decoding JSON response from questions endpoint: {e}")
97
+ print(f"Response text: {response. text[:500]}")
98
+ return f"Error decoding server response for questions: {e}", None
99
  except Exception as e:
100
  print(f"An unexpected error occurred fetching questions: {e}")
101
  return f"An unexpected error occurred fetching questions: {e}", None
 
104
  results_log = []
105
  answers_payload = []
106
  print(f"Running agent on {len(questions_data)} questions...")
107
+ for item in questions_data:
108
+ task_id = item.get("task_id")
 
109
  question_text = item.get("question")
110
+ if not task_id or question_text is None:
111
+ print(f"Skipping item with missing task_id or question: {item}")
112
  continue
113
 
114
  try:
115
  answer = agent(question_text)
116
  answers_payload.append({"task_id": task_id, "answer": answer})
117
+ results_log.append({
118
+ "task_id": task_id,
119
+ "question": question_text[: 50] + ".. .",
120
+ "answer": str(answer)[:100] + "..."
121
+ })
122
  except Exception as e:
123
  print(f"Error processing task {task_id}: {e}")
124
  answers_payload.append({"task_id": task_id, "answer": f"Error: {str(e)}"})
125
 
126
  # 4. Submit answers
127
+ print(f"Submitting {len(answers_payload)} answers to {submit_url}...")
128
  try:
129
+ submit_response = requests.post(
130
+ submit_url,
131
+ json={"answers": answers_payload, "username": username, "agent_code": agent_code},
132
+ timeout=60
133
+ )
134
+ submit_response.raise_for_status()
135
+ result_data = submit_response.json()
136
+ print("Submission response received.")
 
 
 
 
 
 
 
 
 
137
  except requests.exceptions.RequestException as e:
138
  print(f"Error submitting answers: {e}")
139
  return f"Error submitting answers: {e}", pd.DataFrame(results_log)
140
+ except requests.exceptions.JSONDecodeError as e:
141
+ print(f"Error decoding submit response JSON: {e}")
142
+ print(f"Response text: {submit_response.text[:500]}")
143
+ return f"Error decoding server response after submitting answers: {e}", pd. DataFrame(results_log)
144
+ except Exception as e:
145
+ print(f"An unexpected error occurred submitting answers: {e}")
146
+ return f"An unexpected error occurred submitting answers: {e}", pd. DataFrame(results_log)
147
+
148
+ # Format the results for display
149
+ try:
150
+ # If result_data is a dict with results list
151
+ if isinstance(result_data, dict):
152
+ score_str = result_data.get('score', "N/A")
153
+ df = pd.DataFrame(results_log)
154
+ else:
155
+ df = pd.DataFrame(result_data)
156
+ score_str = "N/A"
157
+ print("Results dataframe created.")
158
  except Exception as e:
159
+ print(f"Error creating results dataframe: {e}")
160
+ df = pd.DataFrame(results_log)
161
+ score_str = "N/A"
162
+
163
+ result_message = f"✅ Submission completed! Score: {score_str}\n\n[View Agent Codebase]({agent_code})"
164
+ return result_message, df
165
 
 
166
  with gr.Blocks() as demo:
167
+ gr.Markdown("<h1 align='center'>🤖 Agent Final Assignment</h1>")
168
+ gr.Markdown("To see your score, log in using the Hugging Face button below and click 'Run & Submit'.")
169
 
170
  with gr.Row():
171
+ profile = gr.OAuthProfile()
172
 
173
+ with gr.Row():
174
+ run_button = gr.Button("🚀 Run & Submit Agent", variant="primary")
175
 
176
+ result_md = gr.Markdown()
177
+ result_table = gr.Dataframe(label="Results Preview")
178
+
179
+ def run_wrapper(profile):
180
+ result, df = run_and_submit_all(profile)
181
+ return result, df
182
+
183
+ run_button.click(
184
+ run_wrapper,
185
+ inputs=[profile],
186
+ outputs=[result_md, result_table]
187
  )
188
 
189
+ demo.launch()