vtony commited on
Commit
ee97348
·
verified ·
1 Parent(s): f235500

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +218 -0
app.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+ from agent import agent_graph, system_prompt
7
+ from langchain_core.messages import SystemMessage, HumanMessage
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
+ # ... (other imports and constants remain the same) ...
17
+
18
+ # ... (rest of the file remains unchanged) ...
19
+ class BasicAgent:
20
+ def __init__(self):
21
+ print("BasicAgent initialized.")
22
+ self.graph = agent_graph
23
+ def __call__(self, question: str) -> str:
24
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
25
+ # Create initial state with system prompt
26
+ initial_state = {
27
+ "messages": [
28
+ SystemMessage(content=system_prompt),
29
+ HumanMessage(content=question)
30
+ ]
31
+ }
32
+
33
+ # Run the graph
34
+ response = self.graph.invoke(initial_state)
35
+
36
+ # Extract the final AI message
37
+ final_message = response["messages"][-1].content
38
+
39
+ # Extract final answer if formatted with "FINAL ANSWER:"
40
+ if "FINAL ANSWER:" in final_message:
41
+ return final_message.split("FINAL ANSWER:")[-1].strip()
42
+ return final_message
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.")
57
+ return "Please Login to Hugging Face with the button.", None
58
+
59
+ api_url = DEFAULT_API_URL
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)
125
+ response.raise_for_status()
126
+ result_data = response.json()
127
+ final_status = (
128
+ f"Submission Successful!\n"
129
+ f"User: {result_data.get('username')}\n"
130
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
131
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
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)