devasurya commited on
Commit
d705049
·
verified ·
1 Parent(s): b77860e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +237 -1
app.py CHANGED
@@ -19,7 +19,243 @@ class BasicAgent:
19
  print("BasicAgent initialized.")
20
  def __call__(self, question: str, file_path: str) -> str:
21
  print(f"Agent received question (first 50 chars): {question[:50]}...")
22
- #agent_response = agent.run(question)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  config = {"configurable": {}}
24
  if file_path:
25
  config = {"configurable": {"file_path": file_path}}
 
19
  print("BasicAgent initialized.")
20
  def __call__(self, question: str, file_path: str) -> str:
21
  print(f"Agent received question (first 50 chars): {question[:50]}...")
22
+ config = {"configurable": {}}
23
+ if file_path:
24
+ config = {"configurable": {"file_path": file_path}}
25
+ messages = [HumanMessage(content=f"{question}")]
26
+ agent_response = react_agent.invoke({"messages": messages}, config=config, debug=True)
27
+ agent_response = agent_response["messages"][-1].content
28
+ agent_response = agent_response.strip()
29
+ print(f"Agent returning fixed answer: {agent_response}")
30
+ return agent_response
31
+
32
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
33
+ """
34
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
35
+ and displays the results.
36
+ """
37
+ # --- Determine HF Space Runtime URL and Repo URL ---
38
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
39
+
40
+ if profile:
41
+ username= f"{profile.username}"
42
+ print(f"User logged in: {username}")
43
+ else:
44
+ print("User not logged in.")
45
+ return "Please Login to Hugging Face with the button.", None
46
+
47
+ api_url = DEFAULT_API_URL
48
+ questions_url = f"{api_url}/questions"
49
+ submit_url = f"{api_url}/submit"
50
+ file_url = f"{api_url}/files"
51
+
52
+ # 1. Instantiate Agent ( modify this part to create your agent)
53
+ try:
54
+ agent = BasicAgent()
55
+ except Exception as e:
56
+ print(f"Error instantiating agent: {e}")
57
+ return f"Error initializing agent: {e}", None
58
+ # 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)
59
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
60
+ print(agent_code)
61
+
62
+ # 2. Fetch Questions
63
+ print(f"Fetching questions from: {questions_url}")
64
+ try:
65
+ response = requests.get(questions_url, timeout=15)
66
+ response.raise_for_status()
67
+ questions_data = response.json()
68
+ if not questions_data:
69
+ print("Fetched questions list is empty.")
70
+ return "Fetched questions list is empty or invalid format.", None
71
+ print(f"Fetched {len(questions_data)} questions.")
72
+ except requests.exceptions.RequestException as e:
73
+ print(f"Error fetching questions: {e}")
74
+ return f"Error fetching questions: {e}", None
75
+ except requests.exceptions.JSONDecodeError as e:
76
+ print(f"Error decoding JSON response from questions endpoint: {e}")
77
+ print(f"Response text: {response.text[:500]}")
78
+ return f"Error decoding server response for questions: {e}", None
79
+ except Exception as e:
80
+ print(f"An unexpected error occurred fetching questions: {e}")
81
+ return f"An unexpected error occurred fetching questions: {e}", None
82
+
83
+ # 3. Run your Agent
84
+ results_log = []
85
+ answers_payload = []
86
+ print(f"Running agent on {len(questions_data)} questions...")
87
+ for item in questions_data:
88
+ task_id = item.get("task_id")
89
+ question_text = item.get("question")
90
+ file_name = item.get("file_name")
91
+
92
+ file_path = None # Ensure file_path is always defined
93
+
94
+ if file_name:
95
+ # Ensure the documents directory exists
96
+ documents_dir = "documents"
97
+ os.makedirs(documents_dir, exist_ok=True)
98
+
99
+ # Clear the documents directory
100
+ for file in os.listdir(documents_dir):
101
+ file_path = os.path.join(documents_dir, file)
102
+ if os.path.isfile(file_path):
103
+ os.remove(file_path)
104
+
105
+ # Download the file
106
+ file_download_url = f"{file_url}/{task_id}"
107
+ try:
108
+ file_response = requests.get(file_download_url, timeout=15)
109
+ file_response.raise_for_status()
110
+ file_path = os.path.join(documents_dir, file_name)
111
+ with open(file_path, "wb") as f:
112
+ f.write(file_response.content)
113
+ print(f"File downloaded and saved to: {file_path}")
114
+ except requests.exceptions.RequestException as e:
115
+ print(f"Error downloading file for task {task_id}: {e}")
116
+ continue
117
+
118
+ question_text += f" (File Name: {file_name})"
119
+
120
+
121
+ if not task_id or question_text is None:
122
+ print(f"Skipping item with missing task_id or question: {item}")
123
+ continue
124
+ try:
125
+ submitted_answer = agent(question_text, file_path)
126
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
127
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
128
+ except Exception as e:
129
+ print(f"Error running agent on task {task_id}: {e}")
130
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
131
+
132
+ if not answers_payload:
133
+ print("Agent did not produce any answers to submit.")
134
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
135
+
136
+ # 4. Prepare Submission
137
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
138
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
139
+ print(status_update)
140
+
141
+ # 5. Submit
142
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
143
+ try:
144
+ response = requests.post(submit_url, json=submission_data, timeout=60)
145
+ response.raise_for_status()
146
+ result_data = response.json()
147
+ final_status = (
148
+ f"Submission Successful!\n"
149
+ f"User: {result_data.get('username')}\n"
150
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
151
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
152
+ f"Message: {result_data.get('message', 'No message received.')}"
153
+ )
154
+ print("Submission successful.")
155
+ results_df = pd.DataFrame(results_log)
156
+ return final_status, results_df
157
+ except requests.exceptions.HTTPError as e:
158
+ error_detail = f"Server responded with status {e.response.status_code}."
159
+ try:
160
+ error_json = e.response.json()
161
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
162
+ except requests.exceptions.JSONDecodeError:
163
+ error_detail += f" Response: {e.response.text[:500]}"
164
+ status_message = f"Submission Failed: {error_detail}"
165
+ print(status_message)
166
+ results_df = pd.DataFrame(results_log)
167
+ return status_message, results_df
168
+ except requests.exceptions.Timeout:
169
+ status_message = "Submission Failed: The request timed out."
170
+ print(status_message)
171
+ results_df = pd.DataFrame(results_log)
172
+ return status_message, results_df
173
+ except requests.exceptions.RequestException as e:
174
+ status_message = f"Submission Failed: Network error - {e}"
175
+ print(status_message)
176
+ results_df = pd.DataFrame(results_log)
177
+ return status_message, results_df
178
+ except Exception as e:
179
+ status_message = f"An unexpected error occurred during submission: {e}"
180
+ print(status_message)
181
+ results_df = pd.DataFrame(results_log)
182
+ return status_message, results_df
183
+
184
+
185
+ # --- Build Gradio Interface using Blocks ---
186
+ with gr.Blocks() as demo:
187
+ gr.Markdown("# Basic Agent Evaluation Runner")
188
+ gr.Markdown(
189
+ """
190
+ **Instructions:**
191
+
192
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
193
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
194
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
195
+
196
+ ---
197
+ **Disclaimers:**
198
+ 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).
199
+ 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.
200
+ """
201
+ )
202
+
203
+ gr.LoginButton()
204
+
205
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
206
+
207
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
208
+ # Removed max_rows=10 from DataFrame constructor
209
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
210
+
211
+ run_button.click(
212
+ fn=run_and_submit_all,
213
+ outputs=[status_output, results_table]
214
+ )
215
+
216
+ if __name__ == "__main__":
217
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
218
+ # Check for SPACE_HOST and SPACE_ID at startup for information
219
+ space_host_startup = os.getenv("SPACE_HOST")
220
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
221
+
222
+ if space_host_startup:
223
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
224
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
225
+ else:
226
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
227
+
228
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
229
+ print(f"✅ SPACE_ID found: {space_id_startup}")
230
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
231
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
232
+ else:
233
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
234
+
235
+ print("-"*(60 + len(" App Starting ")) + "\n")
236
+
237
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
238
+ demo.launch(debug=True, share=False)import os
239
+ import gradio as gr
240
+ import requests
241
+ import inspect
242
+ import pandas as pd
243
+ from langchain_core.messages import HumanMessage
244
+
245
+ from langgraph_agent import react_agent
246
+
247
+
248
+ # (Keep Constants as is)
249
+ # --- Constants ---
250
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
251
+
252
+ # --- Basic Agent Definition ---
253
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
254
+ class BasicAgent:
255
+ def __init__(self):
256
+ print("BasicAgent initialized.")
257
+ def __call__(self, question: str, file_path: str) -> str:
258
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
259
  config = {"configurable": {}}
260
  if file_path:
261
  config = {"configurable": {"file_path": file_path}}