Vani7065 commited on
Commit
1f9878c
·
verified ·
1 Parent(s): f811601

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -92
app.py CHANGED
@@ -4,21 +4,21 @@ import requests
4
  import inspect
5
  import pandas as pd
6
  from openai import OpenAI
7
- import os
8
 
9
- # (Keep Constants as is)
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
13
  # --- Basic Agent Definition ---
14
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
15
-
16
-
17
  class BasicAgent:
18
  def __init__(self):
19
  self.api_key = os.getenv("OPENAI_API_KEY")
20
  if not self.api_key:
21
  raise ValueError("OpenAI API key not found. Please set OPENAI_API_KEY as environment variable.")
 
 
 
 
 
22
  self.client = OpenAI(api_key=self.api_key)
23
  print("✅ OpenAI Agent initialized (v1+ syntax).")
24
 
@@ -41,16 +41,12 @@ class BasicAgent:
41
  print(f"❌ Error calling OpenAI API: {e}")
42
  return f"ERROR: {e}"
43
 
44
- def run_and_submit_all( profile: gr.OAuthProfile | None):
45
- """
46
- Fetches all questions, runs the BasicAgent on them, submits all answers,
47
- and displays the results.
48
- """
49
- # --- Determine HF Space Runtime URL and Repo URL ---
50
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
51
 
52
  if profile:
53
- username= f"{profile.username}"
54
  print(f"User logged in: {username}")
55
  else:
56
  print("User not logged in.")
@@ -60,65 +56,61 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
60
  questions_url = f"{api_url}/questions"
61
  submit_url = f"{api_url}/submit"
62
 
63
- # 1. Instantiate Agent ( modify this part to create your agent)
64
  try:
65
  agent = BasicAgent()
66
  except Exception as e:
67
  print(f"Error instantiating agent: {e}")
68
  return f"Error initializing agent: {e}", None
69
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
70
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
71
  print(agent_code)
72
 
73
- # 2. Fetch Questions
74
  print(f"Fetching questions from: {questions_url}")
75
  try:
76
  response = requests.get(questions_url, timeout=15)
77
  response.raise_for_status()
78
  questions_data = response.json()
79
  if not questions_data:
80
- print("Fetched questions list is empty.")
81
- return "Fetched questions list is empty or invalid format.", None
82
  print(f"Fetched {len(questions_data)} questions.")
83
  except requests.exceptions.RequestException as e:
84
  print(f"Error fetching questions: {e}")
85
  return f"Error fetching questions: {e}", None
86
  except requests.exceptions.JSONDecodeError as e:
87
- print(f"Error decoding JSON response from questions endpoint: {e}")
88
- print(f"Response text: {response.text[:500]}")
89
- return f"Error decoding server response for questions: {e}", None
90
  except Exception as e:
91
- print(f"An unexpected error occurred fetching questions: {e}")
92
- return f"An unexpected error occurred fetching questions: {e}", None
93
 
94
- # 3. Run your Agent
95
  results_log = []
96
  answers_payload = []
 
97
  print(f"Running agent on {len(questions_data)} questions...")
98
  for item in questions_data:
99
  task_id = item.get("task_id")
100
  question_text = item.get("question")
101
  if not task_id or question_text is None:
102
- print(f"Skipping item with missing task_id or question: {item}")
103
  continue
104
  try:
105
  submitted_answer = agent(question_text)
106
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
107
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
108
  except Exception as e:
109
- print(f"Error running agent on task {task_id}: {e}")
110
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
111
 
112
  if not answers_payload:
113
- print("Agent did not produce any answers to submit.")
114
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
115
 
116
- # 4. Prepare Submission
117
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
118
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
119
- print(status_update)
 
120
 
121
- # 5. Submit
122
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
123
  try:
124
  response = requests.post(submit_url, json=submission_data, timeout=60)
@@ -132,87 +124,56 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
132
  f"Message: {result_data.get('message', 'No message received.')}"
133
  )
134
  print("Submission successful.")
135
- results_df = pd.DataFrame(results_log)
136
- return final_status, results_df
137
  except requests.exceptions.HTTPError as e:
138
- error_detail = f"Server responded with status {e.response.status_code}."
139
  try:
140
- error_json = e.response.json()
141
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
142
- except requests.exceptions.JSONDecodeError:
143
- error_detail += f" Response: {e.response.text[:500]}"
144
- status_message = f"Submission Failed: {error_detail}"
145
- print(status_message)
146
- results_df = pd.DataFrame(results_log)
147
- return status_message, results_df
148
  except requests.exceptions.Timeout:
149
- status_message = "Submission Failed: The request timed out."
150
- print(status_message)
151
- results_df = pd.DataFrame(results_log)
152
- return status_message, results_df
153
  except requests.exceptions.RequestException as e:
154
- status_message = f"Submission Failed: Network error - {e}"
155
- print(status_message)
156
- results_df = pd.DataFrame(results_log)
157
- return status_message, results_df
158
  except Exception as e:
159
- status_message = f"An unexpected error occurred during submission: {e}"
160
- print(status_message)
161
- results_df = pd.DataFrame(results_log)
162
- return status_message, results_df
163
 
164
 
165
- # --- Build Gradio Interface using Blocks ---
166
  with gr.Blocks() as demo:
167
  gr.Markdown("# Basic Agent Evaluation Runner")
168
- gr.Markdown(
169
- """
170
  **Instructions:**
171
-
172
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
173
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
174
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
175
-
176
- ---
177
- **Disclaimers:**
178
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
179
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
180
- """
181
- )
182
 
183
  gr.LoginButton()
184
-
185
  run_button = gr.Button("Run Evaluation & Submit All Answers")
186
 
187
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
188
- # Removed max_rows=10 from DataFrame constructor
189
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
190
 
191
- run_button.click(
192
- fn=run_and_submit_all,
193
- outputs=[status_output, results_table]
194
- )
195
 
196
  if __name__ == "__main__":
197
  print("\n" + "-"*30 + " App Starting " + "-"*30)
198
- # Check for SPACE_HOST and SPACE_ID at startup for information
199
- space_host_startup = os.getenv("SPACE_HOST")
200
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
201
 
202
- if space_host_startup:
203
- print(f"✅ SPACE_HOST found: {space_host_startup}")
204
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
205
  else:
206
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
207
 
208
- if space_id_startup: # Print repo URLs if SPACE_ID is found
209
- print(f"✅ SPACE_ID found: {space_id_startup}")
210
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
211
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
212
  else:
213
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
214
-
215
- print("-"*(60 + len(" App Starting ")) + "\n")
216
 
217
- print("Launching Gradio Interface for Basic Agent Evaluation...")
218
- demo.launch(debug=True, share=False)
 
 
4
  import inspect
5
  import pandas as pd
6
  from openai import OpenAI
 
7
 
 
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
  # --- Basic Agent Definition ---
 
 
 
12
  class BasicAgent:
13
  def __init__(self):
14
  self.api_key = os.getenv("OPENAI_API_KEY")
15
  if not self.api_key:
16
  raise ValueError("OpenAI API key not found. Please set OPENAI_API_KEY as environment variable.")
17
+
18
+ # Optional: Log OpenAI constructor arguments
19
+ print("🔍 OpenAI init params:", list(inspect.signature(OpenAI.__init__).parameters.keys()))
20
+
21
+ # ✅ Ensure only valid args passed
22
  self.client = OpenAI(api_key=self.api_key)
23
  print("✅ OpenAI Agent initialized (v1+ syntax).")
24
 
 
41
  print(f"❌ Error calling OpenAI API: {e}")
42
  return f"ERROR: {e}"
43
 
44
+
45
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
46
+ space_id = os.getenv("SPACE_ID")
 
 
 
 
47
 
48
  if profile:
49
+ username = f"{profile.username}"
50
  print(f"User logged in: {username}")
51
  else:
52
  print("User not logged in.")
 
56
  questions_url = f"{api_url}/questions"
57
  submit_url = f"{api_url}/submit"
58
 
 
59
  try:
60
  agent = BasicAgent()
61
  except Exception as e:
62
  print(f"Error instantiating agent: {e}")
63
  return f"Error initializing agent: {e}", None
64
+
65
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
66
  print(agent_code)
67
 
 
68
  print(f"Fetching questions from: {questions_url}")
69
  try:
70
  response = requests.get(questions_url, timeout=15)
71
  response.raise_for_status()
72
  questions_data = response.json()
73
  if not questions_data:
74
+ print("Fetched questions list is empty.")
75
+ return "Fetched questions list is empty or invalid format.", None
76
  print(f"Fetched {len(questions_data)} questions.")
77
  except requests.exceptions.RequestException as e:
78
  print(f"Error fetching questions: {e}")
79
  return f"Error fetching questions: {e}", None
80
  except requests.exceptions.JSONDecodeError as e:
81
+ print(f"Error decoding JSON response: {e}")
82
+ return f"Error decoding server response for questions: {e}", None
 
83
  except Exception as e:
84
+ print(f"Unexpected error fetching questions: {e}")
85
+ return f"Unexpected error fetching questions: {e}", None
86
 
 
87
  results_log = []
88
  answers_payload = []
89
+
90
  print(f"Running agent on {len(questions_data)} questions...")
91
  for item in questions_data:
92
  task_id = item.get("task_id")
93
  question_text = item.get("question")
94
  if not task_id or question_text is None:
95
+ print(f"Skipping invalid item: {item}")
96
  continue
97
  try:
98
  submitted_answer = agent(question_text)
99
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
100
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
101
  except Exception as e:
102
+ print(f"Error running agent on task {task_id}: {e}")
103
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
104
 
105
  if not answers_payload:
 
106
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
107
 
108
+ submission_data = {
109
+ "username": username.strip(),
110
+ "agent_code": agent_code,
111
+ "answers": answers_payload
112
+ }
113
 
 
114
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
115
  try:
116
  response = requests.post(submit_url, json=submission_data, timeout=60)
 
124
  f"Message: {result_data.get('message', 'No message received.')}"
125
  )
126
  print("Submission successful.")
127
+ return final_status, pd.DataFrame(results_log)
 
128
  except requests.exceptions.HTTPError as e:
 
129
  try:
130
+ error_detail = f"{e.response.status_code} - {e.response.json().get('detail', e.response.text)}"
131
+ except Exception:
132
+ error_detail = f"{e.response.status_code} - {e.response.text}"
133
+ return f"Submission Failed: {error_detail}", pd.DataFrame(results_log)
 
 
 
 
134
  except requests.exceptions.Timeout:
135
+ return "Submission Failed: The request timed out.", pd.DataFrame(results_log)
 
 
 
136
  except requests.exceptions.RequestException as e:
137
+ return f"Submission Failed: Network error - {e}", pd.DataFrame(results_log)
 
 
 
138
  except Exception as e:
139
+ return f"Unexpected error during submission: {e}", pd.DataFrame(results_log)
 
 
 
140
 
141
 
142
+ # --- Gradio Interface ---
143
  with gr.Blocks() as demo:
144
  gr.Markdown("# Basic Agent Evaluation Runner")
145
+ gr.Markdown("""
 
146
  **Instructions:**
147
+ 1. Clone this space and modify the code to define your own agent.
148
+ 2. Log in with your Hugging Face account.
149
+ 3. Click 'Run Evaluation & Submit All Answers' to start.
150
+ """)
 
 
 
 
 
 
 
151
 
152
  gr.LoginButton()
 
153
  run_button = gr.Button("Run Evaluation & Submit All Answers")
154
 
155
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
156
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
157
 
158
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
159
 
160
  if __name__ == "__main__":
161
  print("\n" + "-"*30 + " App Starting " + "-"*30)
162
+ space_host = os.getenv("SPACE_HOST")
163
+ space_id = os.getenv("SPACE_ID")
 
164
 
165
+ if space_host:
166
+ print(f"✅ SPACE_HOST: {space_host}")
167
+ print(f"Runtime URL: https://{space_host}.hf.space")
168
  else:
169
+ print("ℹ️ SPACE_HOST not found.")
170
 
171
+ if space_id:
172
+ print(f"✅ SPACE_ID: {space_id}")
173
+ print(f"Repo: https://huggingface.co/spaces/{space_id}/tree/main")
 
174
  else:
175
+ print("ℹ️ SPACE_ID not found.")
 
 
176
 
177
+ print("-" * 70)
178
+ print("Launching Gradio Interface...")
179
+ demo.launch(debug=True, share=False)