Snaseem2026 commited on
Commit
ca41468
·
verified ·
1 Parent(s): b5f3ffd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -23
app.py CHANGED
@@ -4,7 +4,7 @@ import requests
4
  import pandas as pd
5
 
6
  # --- Constants ---
7
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
8
 
9
  # --- Basic Agent Definition ---
10
  class BasicAgent:
@@ -19,7 +19,7 @@ class BasicAgent:
19
 
20
  # Try to provide context-aware answers
21
  if "capital" in question_lower:
22
- if "france" in question_lower:
23
  return "Paris"
24
  elif "germany" in question_lower:
25
  return "Berlin"
@@ -31,9 +31,9 @@ class BasicAgent:
31
  return "Tokyo"
32
 
33
  if "who" in question_lower and "ceo" in question_lower:
34
- if "tesla" in question_lower or "spacex" in question_lower:
35
  return "Elon Musk"
36
- elif "apple" in question_lower:
37
  return "Tim Cook"
38
  elif "microsoft" in question_lower:
39
  return "Satya Nadella"
@@ -41,13 +41,13 @@ class BasicAgent:
41
  if "what year" in question_lower or "when" in question_lower:
42
  if "world war 2" in question_lower or "wwii" in question_lower:
43
  return "1939-1945"
44
- elif "world war 1" in question_lower or "wwi" in question_lower:
45
  return "1914-1918"
46
 
47
- if "how many" in question_lower:
48
  if "planets" in question_lower:
49
  return "8"
50
- elif "continents" in question_lower:
51
  return "7"
52
 
53
  # Default response
@@ -74,7 +74,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
74
  submit_url = f"{api_url}/submit"
75
 
76
  # 1. Instantiate Agent
77
- try:
78
  agent = BasicAgent()
79
  except Exception as e:
80
  print(f"Error instantiating agent: {e}")
@@ -85,12 +85,12 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
85
  print(f"Agent code: {agent_code}")
86
 
87
  # 2. Fetch Questions
88
- print(f"Fetching questions from: {questions_url}")
89
  try:
90
  response = requests.get(questions_url, timeout=15)
91
  response.raise_for_status()
92
  questions_data = response.json()
93
- if not questions_data:
94
  print("Fetched questions list is empty.")
95
  return "Fetched questions list is empty or invalid format.", None
96
  print(f"Fetched {len(questions_data)} questions.")
@@ -100,7 +100,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
100
  except requests.exceptions.JSONDecodeError as e:
101
  print(f"Error decoding JSON response from questions endpoint: {e}")
102
  print(f"Response text: {response.text[: 500]}")
103
- return f"Error decoding server response for questions: {e}", None
104
  except Exception as e:
105
  print(f"An unexpected error occurred fetching questions: {e}")
106
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -109,29 +109,36 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
109
  results_log = []
110
  answers_payload = []
111
  print(f"Running agent on {len(questions_data)} questions...")
112
- for item in questions_data:
113
  task_id = item.get("task_id")
114
  question_text = item.get("question")
115
- if not task_id or question_text is None:
116
  print(f"Skipping item with missing task_id or question: {item}")
117
  continue
118
 
119
  try:
120
  answer = agent(question_text)
121
- answers_payload.append({"task_id": task_id, "answer": answer})
122
- results_log.append((task_id, question_text[: 50], answer[: 100]))
 
 
 
 
123
  except Exception as e:
124
  print(f"Error running agent on question {task_id}: {e}")
125
- answers_payload.append({"task_id": task_id, "answer": f"Error: {e}"})
 
 
 
126
  results_log.append((task_id, question_text[:50], f"Error: {e}"))
127
 
128
  # 4. Submit answers with CORRECT payload format
129
  print(f"Submitting {len(answers_payload)} answers to {submit_url}...")
130
  try:
131
- # THIS IS THE CORRECT PAYLOAD FORMAT!
132
  payload = {
133
  "username": username,
134
- "answers": answers_payload,
135
  "agent_code": agent_code
136
  }
137
 
@@ -144,11 +151,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
144
  )
145
  submit_response.raise_for_status()
146
  submission_result = submit_response.json()
147
- print(f"Submission successful: {submission_result}")
148
  except requests.exceptions.HTTPError as e:
149
  print(f"HTTP Error submitting answers: {e}")
150
- print(f"Response text: {submit_response.text[: 500]}")
151
- return f"Error submitting answers: {e}\n\nResponse: {submit_response.text[: 200]}", None
152
  except Exception as e:
153
  print(f"Error submitting answers: {e}")
154
  return f"Error submitting answers: {e}", None
@@ -159,7 +166,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
159
  # Extract score from submission result
160
  score = submission_result.get('score', 'N/A')
161
  result_message = f"""
162
- ## ✅ Submission Successful!
163
 
164
  **Score:** {score}
165
 
@@ -192,7 +199,7 @@ with gr.Blocks() as demo:
192
  output_text = gr. Markdown()
193
  output_table = gr.Dataframe(label="Results")
194
 
195
- # The profile is automatically injected when using gr.LoginButton()
196
  submit_button.click(
197
  run_and_submit_all,
198
  inputs=None,
 
4
  import pandas as pd
5
 
6
  # --- Constants ---
7
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf. space"
8
 
9
  # --- Basic Agent Definition ---
10
  class BasicAgent:
 
19
 
20
  # Try to provide context-aware answers
21
  if "capital" in question_lower:
22
+ if "france" in question_lower:
23
  return "Paris"
24
  elif "germany" in question_lower:
25
  return "Berlin"
 
31
  return "Tokyo"
32
 
33
  if "who" in question_lower and "ceo" in question_lower:
34
+ if "tesla" in question_lower or "spacex" in question_lower:
35
  return "Elon Musk"
36
+ elif "apple" in question_lower:
37
  return "Tim Cook"
38
  elif "microsoft" in question_lower:
39
  return "Satya Nadella"
 
41
  if "what year" in question_lower or "when" in question_lower:
42
  if "world war 2" in question_lower or "wwii" in question_lower:
43
  return "1939-1945"
44
+ elif "world war 1" in question_lower or "wwi" in question_lower:
45
  return "1914-1918"
46
 
47
+ if "how many" in question_lower:
48
  if "planets" in question_lower:
49
  return "8"
50
+ elif "continents" in question_lower:
51
  return "7"
52
 
53
  # Default response
 
74
  submit_url = f"{api_url}/submit"
75
 
76
  # 1. Instantiate Agent
77
+ try:
78
  agent = BasicAgent()
79
  except Exception as e:
80
  print(f"Error instantiating agent: {e}")
 
85
  print(f"Agent code: {agent_code}")
86
 
87
  # 2. Fetch Questions
88
+ print(f"Fetching questions from: {questions_url}")
89
  try:
90
  response = requests.get(questions_url, timeout=15)
91
  response.raise_for_status()
92
  questions_data = response.json()
93
+ if not questions_data:
94
  print("Fetched questions list is empty.")
95
  return "Fetched questions list is empty or invalid format.", None
96
  print(f"Fetched {len(questions_data)} questions.")
 
100
  except requests.exceptions.JSONDecodeError as e:
101
  print(f"Error decoding JSON response from questions endpoint: {e}")
102
  print(f"Response text: {response.text[: 500]}")
103
+ return f"Error decoding server response for questions: {e}", None
104
  except Exception as e:
105
  print(f"An unexpected error occurred fetching questions: {e}")
106
  return f"An unexpected error occurred fetching questions: {e}", None
 
109
  results_log = []
110
  answers_payload = []
111
  print(f"Running agent on {len(questions_data)} questions...")
112
+ for item in questions_data:
113
  task_id = item.get("task_id")
114
  question_text = item.get("question")
115
+ if not task_id or question_text is None:
116
  print(f"Skipping item with missing task_id or question: {item}")
117
  continue
118
 
119
  try:
120
  answer = agent(question_text)
121
+ # THE FIX: Use "submitted_answer" not "answer"!
122
+ answers_payload.append({
123
+ "task_id": task_id,
124
+ "submitted_answer": answer # ← Changed from "answer" to "submitted_answer"
125
+ })
126
+ results_log.append((task_id, question_text[:50], answer[: 100]))
127
  except Exception as e:
128
  print(f"Error running agent on question {task_id}: {e}")
129
+ answers_payload.append({
130
+ "task_id": task_id,
131
+ "submitted_answer": f"Error: {e}" # ← Changed here too
132
+ })
133
  results_log.append((task_id, question_text[:50], f"Error: {e}"))
134
 
135
  # 4. Submit answers with CORRECT payload format
136
  print(f"Submitting {len(answers_payload)} answers to {submit_url}...")
137
  try:
138
+ # Correct payload format
139
  payload = {
140
  "username": username,
141
+ "answers": answers_payload,
142
  "agent_code": agent_code
143
  }
144
 
 
151
  )
152
  submit_response.raise_for_status()
153
  submission_result = submit_response.json()
154
+ print(f"Submission successful: {submission_result}")
155
  except requests.exceptions.HTTPError as e:
156
  print(f"HTTP Error submitting answers: {e}")
157
+ print(f"Response text: {submit_response.text[:500]}")
158
+ return f"Error submitting answers: {e}\n\nResponse: {submit_response.text[:200]}", None
159
  except Exception as e:
160
  print(f"Error submitting answers: {e}")
161
  return f"Error submitting answers: {e}", None
 
166
  # Extract score from submission result
167
  score = submission_result.get('score', 'N/A')
168
  result_message = f"""
169
+ ## ✅ Submission Successful!
170
 
171
  **Score:** {score}
172
 
 
199
  output_text = gr. Markdown()
200
  output_table = gr.Dataframe(label="Results")
201
 
202
+ # The profile is automatically injected when using gr. LoginButton()
203
  submit_button.click(
204
  run_and_submit_all,
205
  inputs=None,