Gustavo Gonçalves commited on
Commit
b9e458c
·
1 Parent(s): ac6657c
Files changed (1) hide show
  1. app.py +190 -0
app.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+ from agents import BasicAgent
7
+
8
+ # (Keep Constants as is)
9
+ # --- Constants ---
10
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
+ GAIA_PROMPT = "You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string."
12
+
13
+
14
+ # --- Basic Agent Definition ---
15
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
16
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
17
+ """
18
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
19
+ and displays the results.
20
+ """
21
+ # --- Determine HF Space Runtime URL and Repo URL ---
22
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
23
+
24
+ if profile:
25
+ username= f"{profile.username}"
26
+ print(f"User logged in: {username}")
27
+ else:
28
+ print("User not logged in.")
29
+ return "Please Login to Hugging Face with the button.", None
30
+
31
+ api_url = DEFAULT_API_URL
32
+ questions_url = f"{api_url}/questions"
33
+ submit_url = f"{api_url}/submit"
34
+
35
+ # 1. Instantiate Agent ( modify this part to create your agent)
36
+ try:
37
+ agent = BasicAgent()
38
+ except Exception as e:
39
+ print(f"Error instantiating agent: {e}")
40
+ return f"Error initializing agent: {e}", None
41
+ # 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)
42
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
43
+ print(agent_code)
44
+
45
+ # 2. Fetch Questions
46
+ print(f"Fetching questions from: {questions_url}")
47
+ try:
48
+ response = requests.get(questions_url, timeout=15)
49
+ response.raise_for_status()
50
+ questions_data = response.json()
51
+ if not questions_data:
52
+ print("Fetched questions list is empty.")
53
+ return "Fetched questions list is empty or invalid format.", None
54
+ print(f"Fetched {len(questions_data)} questions.")
55
+ except requests.exceptions.RequestException as e:
56
+ print(f"Error fetching questions: {e}")
57
+ return f"Error fetching questions: {e}", None
58
+ except requests.exceptions.JSONDecodeError as e:
59
+ print(f"Error decoding JSON response from questions endpoint: {e}")
60
+ print(f"Response text: {response.text[:500]}")
61
+ return f"Error decoding server response for questions: {e}", None
62
+ except Exception as e:
63
+ print(f"An unexpected error occurred fetching questions: {e}")
64
+ return f"An unexpected error occurred fetching questions: {e}", None
65
+
66
+ # 3. Run your Agent
67
+ results_log = []
68
+ answers_payload = []
69
+ print(f"Running agent on {len(questions_data)} questions...")
70
+ for item in questions_data:
71
+ task_id = item.get("task_id")
72
+ question_text = item.get("question")
73
+ if not task_id or question_text is None:
74
+ print(f"Skipping item with missing task_id or question: {item}")
75
+ continue
76
+ try:
77
+ submitted_answer = agent(question_text)
78
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
79
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
80
+ except Exception as e:
81
+ print(f"Error running agent on task {task_id}: {e}")
82
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
83
+
84
+ if not answers_payload:
85
+ print("Agent did not produce any answers to submit.")
86
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
87
+
88
+ # 4. Prepare Submission
89
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
90
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
91
+ print(status_update)
92
+
93
+ # 5. Submit
94
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
95
+ try:
96
+ response = requests.post(submit_url, json=submission_data, timeout=60)
97
+ response.raise_for_status()
98
+ result_data = response.json()
99
+ final_status = (
100
+ f"Submission Successful!\n"
101
+ f"User: {result_data.get('username')}\n"
102
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
103
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
104
+ f"Message: {result_data.get('message', 'No message received.')}"
105
+ )
106
+ print("Submission successful.")
107
+ results_df = pd.DataFrame(results_log)
108
+ return final_status, results_df
109
+ except requests.exceptions.HTTPError as e:
110
+ error_detail = f"Server responded with status {e.response.status_code}."
111
+ try:
112
+ error_json = e.response.json()
113
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
114
+ except requests.exceptions.JSONDecodeError:
115
+ error_detail += f" Response: {e.response.text[:500]}"
116
+ status_message = f"Submission Failed: {error_detail}"
117
+ print(status_message)
118
+ results_df = pd.DataFrame(results_log)
119
+ return status_message, results_df
120
+ except requests.exceptions.Timeout:
121
+ status_message = "Submission Failed: The request timed out."
122
+ print(status_message)
123
+ results_df = pd.DataFrame(results_log)
124
+ return status_message, results_df
125
+ except requests.exceptions.RequestException as e:
126
+ status_message = f"Submission Failed: Network error - {e}"
127
+ print(status_message)
128
+ results_df = pd.DataFrame(results_log)
129
+ return status_message, results_df
130
+ except Exception as e:
131
+ status_message = f"An unexpected error occurred during submission: {e}"
132
+ print(status_message)
133
+ results_df = pd.DataFrame(results_log)
134
+ return status_message, results_df
135
+
136
+
137
+ # --- Build Gradio Interface using Blocks ---
138
+ with gr.Blocks() as demo:
139
+ gr.Markdown("# Basic Agent Evaluation Runner")
140
+ gr.Markdown(
141
+ """
142
+ **Instructions:**
143
+
144
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
145
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
146
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
147
+
148
+ ---
149
+ **Disclaimers:**
150
+ 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).
151
+ 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.
152
+ """
153
+ )
154
+
155
+ gr.LoginButton()
156
+
157
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
158
+
159
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
160
+ # Removed max_rows=10 from DataFrame constructor
161
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
162
+
163
+ run_button.click(
164
+ fn=run_and_submit_all,
165
+ outputs=[status_output, results_table]
166
+ )
167
+
168
+ if __name__ == "__main__":
169
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
170
+ # Check for SPACE_HOST and SPACE_ID at startup for information
171
+ space_host_startup = os.getenv("SPACE_HOST")
172
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
173
+
174
+ if space_host_startup:
175
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
176
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
177
+ else:
178
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
179
+
180
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
181
+ print(f"✅ SPACE_ID found: {space_id_startup}")
182
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
183
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
184
+ else:
185
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
186
+
187
+ print("-"*(60 + len(" App Starting ")) + "\n")
188
+
189
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
190
+ demo.launch(debug=True, share=False)