Luong Huu Thanh commited on
Commit
039a1df
Β·
1 Parent(s): df099ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -52
app.py CHANGED
@@ -4,11 +4,11 @@ import inspect
4
  import gradio as gr
5
  import requests
6
  import pandas as pd
7
- import time
8
  from langchain_core.messages import HumanMessage
9
  from agent import build_graph
10
 
11
 
 
12
  # (Keep Constants as is)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -19,7 +19,6 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
19
 
20
  class BasicAgent:
21
  """A langgraph agent."""
22
-
23
  def __init__(self):
24
  print("BasicAgent initialized.")
25
  self.graph = build_graph()
@@ -29,20 +28,20 @@ class BasicAgent:
29
  # Wrap the question in a HumanMessage from langchain_core
30
  messages = [HumanMessage(content=question)]
31
  messages = self.graph.invoke({"messages": messages})
32
- answer = messages["messages"][-1].content
33
  return answer[14:]
34
 
35
 
36
- def run_and_submit_all(profile: gr.OAuthProfile | None):
37
  """
38
  Fetches all questions, runs the BasicAgent on them, submits all answers,
39
  and displays the results.
40
  """
41
  # --- Determine HF Space Runtime URL and Repo URL ---
42
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
43
 
44
  if profile:
45
- username = f"{profile.username}"
46
  print(f"User logged in: {username}")
47
  else:
48
  print("User not logged in.")
@@ -69,16 +68,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
69
  response.raise_for_status()
70
  questions_data = response.json()
71
  if not questions_data:
72
- print("Fetched questions list is empty.")
73
- return "Fetched questions list is empty or invalid format.", None
74
  print(f"Fetched {len(questions_data)} questions.")
75
  except requests.exceptions.RequestException as e:
76
  print(f"Error fetching questions: {e}")
77
  return f"Error fetching questions: {e}", None
78
  except requests.exceptions.JSONDecodeError as e:
79
- print(f"Error decoding JSON response from questions endpoint: {e}")
80
- print(f"Response text: {response.text[:500]}")
81
- return f"Error decoding server response for questions: {e}", None
82
  except Exception as e:
83
  print(f"An unexpected error occurred fetching questions: {e}")
84
  return f"An unexpected error occurred fetching questions: {e}", None
@@ -95,38 +94,18 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
95
  continue
96
  try:
97
  submitted_answer = agent(question_text)
98
- answers_payload.append(
99
- {"task_id": task_id, "submitted_answer": submitted_answer}
100
- )
101
- results_log.append(
102
- {
103
- "Task ID": task_id,
104
- "Question": question_text,
105
- "Submitted Answer": submitted_answer,
106
- }
107
- )
108
- time.sleep(2)
109
  except Exception as e:
110
- print(f"Error running agent on task {task_id}: {e}")
111
- results_log.append(
112
- {
113
- "Task ID": task_id,
114
- "Question": question_text,
115
- "Submitted Answer": f"AGENT ERROR: {e}",
116
- }
117
- )
118
- time.sleep(2)
119
 
120
  if not answers_payload:
121
  print("Agent did not produce any answers to submit.")
122
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
123
 
124
- # 4. Prepare Submission
125
- submission_data = {
126
- "username": username.strip(),
127
- "agent_code": agent_code,
128
- "answers": answers_payload,
129
- }
130
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
131
  print(status_update)
132
 
@@ -194,19 +173,20 @@ with gr.Blocks() as demo:
194
 
195
  run_button = gr.Button("Run Evaluation & Submit All Answers")
196
 
197
- status_output = gr.Textbox(
198
- label="Run Status / Submission Result", lines=5, interactive=False
199
- )
200
  # Removed max_rows=10 from DataFrame constructor
201
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
202
 
203
- run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
 
 
 
204
 
205
  if __name__ == "__main__":
206
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
207
  # Check for SPACE_HOST and SPACE_ID at startup for information
208
  space_host_startup = os.getenv("SPACE_HOST")
209
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
210
 
211
  if space_host_startup:
212
  print(f"βœ… SPACE_HOST found: {space_host_startup}")
@@ -214,18 +194,14 @@ if __name__ == "__main__":
214
  else:
215
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
216
 
217
- if space_id_startup: # Print repo URLs if SPACE_ID is found
218
  print(f"βœ… SPACE_ID found: {space_id_startup}")
219
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
220
- print(
221
- f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
222
- )
223
  else:
224
- print(
225
- "ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
226
- )
227
 
228
- print("-" * (60 + len(" App Starting ")) + "\n")
229
 
230
  print("Launching Gradio Interface for Basic Agent Evaluation...")
231
- demo.launch(debug=True, share=False)
 
4
  import gradio as gr
5
  import requests
6
  import pandas as pd
 
7
  from langchain_core.messages import HumanMessage
8
  from agent import build_graph
9
 
10
 
11
+
12
  # (Keep Constants as is)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
19
 
20
  class BasicAgent:
21
  """A langgraph agent."""
 
22
  def __init__(self):
23
  print("BasicAgent initialized.")
24
  self.graph = build_graph()
 
28
  # Wrap the question in a HumanMessage from langchain_core
29
  messages = [HumanMessage(content=question)]
30
  messages = self.graph.invoke({"messages": messages})
31
+ answer = messages['messages'][-1].content
32
  return answer[14:]
33
 
34
 
35
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
36
  """
37
  Fetches all questions, runs the BasicAgent on them, submits all answers,
38
  and displays the results.
39
  """
40
  # --- Determine HF Space Runtime URL and Repo URL ---
41
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
42
 
43
  if profile:
44
+ username= f"{profile.username}"
45
  print(f"User logged in: {username}")
46
  else:
47
  print("User not logged in.")
 
68
  response.raise_for_status()
69
  questions_data = response.json()
70
  if not questions_data:
71
+ print("Fetched questions list is empty.")
72
+ return "Fetched questions list is empty or invalid format.", None
73
  print(f"Fetched {len(questions_data)} questions.")
74
  except requests.exceptions.RequestException as e:
75
  print(f"Error fetching questions: {e}")
76
  return f"Error fetching questions: {e}", None
77
  except requests.exceptions.JSONDecodeError as e:
78
+ print(f"Error decoding JSON response from questions endpoint: {e}")
79
+ print(f"Response text: {response.text[:500]}")
80
+ return f"Error decoding server response for questions: {e}", None
81
  except Exception as e:
82
  print(f"An unexpected error occurred fetching questions: {e}")
83
  return f"An unexpected error occurred fetching questions: {e}", None
 
94
  continue
95
  try:
96
  submitted_answer = agent(question_text)
97
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
98
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
 
99
  except Exception as e:
100
+ print(f"Error running agent on task {task_id}: {e}")
101
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
102
 
103
  if not answers_payload:
104
  print("Agent did not produce any answers to submit.")
105
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
106
 
107
+ # 4. Prepare Submission
108
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
 
 
 
109
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
110
  print(status_update)
111
 
 
173
 
174
  run_button = gr.Button("Run Evaluation & Submit All Answers")
175
 
176
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
 
177
  # Removed max_rows=10 from DataFrame constructor
178
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
179
 
180
+ run_button.click(
181
+ fn=run_and_submit_all,
182
+ outputs=[status_output, results_table]
183
+ )
184
 
185
  if __name__ == "__main__":
186
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
187
  # Check for SPACE_HOST and SPACE_ID at startup for information
188
  space_host_startup = os.getenv("SPACE_HOST")
189
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
190
 
191
  if space_host_startup:
192
  print(f"βœ… SPACE_HOST found: {space_host_startup}")
 
194
  else:
195
  print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
196
 
197
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
198
  print(f"βœ… SPACE_ID found: {space_id_startup}")
199
  print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
200
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
 
 
201
  else:
202
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
 
 
203
 
204
+ print("-"*(60 + len(" App Starting ")) + "\n")
205
 
206
  print("Launching Gradio Interface for Basic Agent Evaluation...")
207
+ demo.launch(debug=True, share=False)