kpalatel commited on
Commit
0e5be7e
·
verified ·
1 Parent(s): 34e66dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +180 -3
app.py CHANGED
@@ -1,10 +1,187 @@
1
- # Replace your previous BasicAgent definition inside app.py with this import strategy
 
 
 
 
 
 
2
  from agent import CourseEvaluationAgent
3
 
 
 
 
 
4
  class BasicAgent:
5
  def __init__(self):
6
- # Initializes our new externalized architecture agent
7
  self.eval_agent = CourseEvaluationAgent()
8
 
9
  def __call__(self, question: str) -> str:
10
- return self.eval_agent.run_task(question)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+
7
+ # Import our optimized evaluation agent from agent.py
8
  from agent import CourseEvaluationAgent
9
 
10
+ # --- Constants ---
11
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
+
13
+ # --- Basic Agent Wrapper ---
14
  class BasicAgent:
15
  def __init__(self):
16
+ # Instantiate our externalized architecture agent
17
  self.eval_agent = CourseEvaluationAgent()
18
 
19
  def __call__(self, question: str) -> str:
20
+ # Route the evaluation question through our smart agent
21
+ return self.eval_agent.run_task(question)
22
+
23
+
24
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
25
+ """
26
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
27
+ and displays the results.
28
+ """
29
+ # --- Determine HF Space Runtime URL and Repo URL ---
30
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
31
+ if profile:
32
+ username = f"{profile.username}"
33
+ print(f"User logged in: {username}")
34
+ else:
35
+ print("User not logged in.")
36
+ return "Please Login to Hugging Face with the button.", None
37
+
38
+ api_url = DEFAULT_API_URL
39
+ questions_url = f"{api_url}/questions"
40
+ submit_url = f"{api_url}/submit"
41
+
42
+ # 1. Instantiate Agent
43
+ try:
44
+ agent = BasicAgent()
45
+ except Exception as e:
46
+ print(f"Error instantiating agent: {e}")
47
+ return f"Error initializing agent: {e}", None
48
+
49
+ # Link pointing toward your public codebase
50
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
51
+ print(agent_code)
52
+
53
+ # 2. Fetch Questions
54
+ print(f"Fetching questions from: {questions_url}")
55
+ try:
56
+ response = requests.get(questions_url, timeout=15)
57
+ response.raise_for_status()
58
+ questions_data = response.json()
59
+ if not questions_data:
60
+ print("Fetched questions list is empty.")
61
+ return "Fetched questions list is empty or invalid format.", None
62
+ print(f"Fetched {len(questions_data)} questions.")
63
+ except requests.exceptions.RequestException as e:
64
+ print(f"Error fetching questions: {e}")
65
+ return f"Error fetching questions: {e}", None
66
+ except requests.exceptions.JSONDecodeError as e:
67
+ print(f"Error decoding JSON response from questions endpoint: {e}")
68
+ print(f"Response text: {response.text[:500]}")
69
+ return f"Error decoding server response for questions: {e}", None
70
+ except Exception as e:
71
+ print(f"An unexpected error occurred fetching questions: {e}")
72
+ return f"An unexpected error occurred fetching questions: {e}", None
73
+
74
+ # 3. Run your Agent
75
+ results_log = []
76
+ answers_payload = []
77
+ print(f"Running agent on {len(questions_data)} questions...")
78
+ for item in questions_data:
79
+ task_id = item.get("task_id")
80
+ question_text = item.get("question")
81
+ if not task_id or question_text is None:
82
+ print(f"Skipping item with missing task_id or question: {item}")
83
+ continue
84
+ try:
85
+ submitted_answer = agent(question_text)
86
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
87
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
88
+ except Exception as e:
89
+ print(f"Error running agent on task {task_id}: {e}")
90
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
91
+
92
+ if not answers_payload:
93
+ print("Agent did not produce any answers to submit.")
94
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
95
+
96
+ # 4. Prepare Submission
97
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
98
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
99
+ print(status_update)
100
+
101
+ # 5. Submit
102
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
103
+ try:
104
+ response = requests.post(submit_url, json=submission_data, timeout=60)
105
+ response.raise_for_status()
106
+ result_data = response.json()
107
+ final_status = (
108
+ f"Submission Successful!\n"
109
+ f"User: {result_data.get('username')}\n"
110
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
111
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
112
+ f"Message: {result_data.get('message', 'No message received.')}"
113
+ )
114
+ print("Submission successful.")
115
+ results_df = pd.DataFrame(results_log)
116
+ return final_status, results_df
117
+ except requests.exceptions.HTTPError as e:
118
+ error_detail = f"Server responded with status {e.response.status_code}."
119
+ try:
120
+ error_json = e.response.json()
121
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
122
+ except requests.exceptions.JSONDecodeError:
123
+ error_detail += f" Response: {e.response.text[:500]}"
124
+ status_message = f"Submission Failed: {error_detail}"
125
+ print(status_message)
126
+ results_df = pd.DataFrame(results_log)
127
+ return status_message, results_df
128
+ except requests.exceptions.Timeout:
129
+ status_message = "Submission Failed: The request timed out."
130
+ print(status_message)
131
+ results_df = pd.DataFrame(results_log)
132
+ return status_message, results_df
133
+ except requests.exceptions.RequestException as e:
134
+ status_message = f"Submission Failed: Network error - {e}"
135
+ print(status_message)
136
+ results_df = pd.DataFrame(results_log)
137
+ return status_message, results_df
138
+ except Exception as e:
139
+ status_message = f"An unexpected error occurred during submission: {e}"
140
+ print(status_message)
141
+ results_df = pd.DataFrame(results_log)
142
+ return status_message, results_df
143
+
144
+ # --- Build Gradio Interface using Blocks ---
145
+ with gr.Blocks() as demo:
146
+ gr.Markdown("# Smart Agent Evaluation Runner")
147
+ gr.Markdown(
148
+ """
149
+ **Instructions:**
150
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
+ ---
154
+ **Disclaimers:**
155
+ 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).
156
+ 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.
157
+ """
158
+ )
159
+ gr.LoginButton()
160
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
161
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
162
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
163
+
164
+ run_button.click(
165
+ fn=run_and_submit_all,
166
+ outputs=[status_output, results_table]
167
+ )
168
+
169
+ if __name__ == "__main__":
170
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
171
+ space_host_startup = os.getenv("SPACE_HOST")
172
+ space_id_startup = os.getenv("SPACE_ID")
173
+ if space_host_startup:
174
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
175
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
176
+ else:
177
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
178
+ if space_id_startup:
179
+ print(f"✅ SPACE_ID found: {space_id_startup}")
180
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
181
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
182
+ else:
183
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
184
+ print("-"*(60 + len(" App Starting ")) + "\n")
185
+
186
+ print("Launching Gradio Interface for Smart Agent Evaluation...")
187
+ demo.launch(debug=True, share=False)