melomba2 commited on
Commit
144af19
·
verified ·
1 Parent(s): 61f702a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -16
app.py CHANGED
@@ -5,10 +5,12 @@ import inspect
5
  import pandas as pd
6
  import google.generativeai as genai
7
  import spaces
 
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 ------
@@ -39,10 +41,10 @@ class BasicAgent:
39
  print(f"Error calling Gemini API: {e}")
40
  return f"Error during Gemini API call: {e}"
41
  @spaces.GPU
42
- def run_and_submit_all( profile: gr.OAuthProfile | None):
43
  """
44
- Fetches all questions, runs the BasicAgent on them, submits all answers,
45
- and displays the results.
46
  """
47
  # --- Determine HF Space Runtime URL and Repo URL ---
48
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
@@ -89,23 +91,48 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
89
  print(f"An unexpected error occurred fetching questions: {e}")
90
  return f"An unexpected error occurred fetching questions: {e}", None
91
 
92
- # 3. Run your Agent
93
- results_log = []
94
- answers_payload = []
95
- print(f"Running agent on {len(questions_data)} questions...")
96
- for item in questions_data:
97
  task_id = item.get("task_id")
98
  question_text = item.get("question")
 
99
  if not task_id or question_text is None:
100
  print(f"Skipping item with missing task_id or question: {item}")
101
- continue
 
 
 
 
 
 
 
 
 
 
102
  try:
103
- submitted_answer = agent(question_text)
104
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
105
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
106
  except Exception as e:
107
- print(f"Error running agent on task {task_id}: {e}")
108
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
 
 
 
109
 
110
  if not answers_payload:
111
  print("Agent did not produce any answers to submit.")
@@ -166,11 +193,9 @@ with gr.Blocks() as demo:
166
  gr.Markdown(
167
  """
168
  **Instructions:**
169
-
170
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
171
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
172
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
173
-
174
  ---
175
  **Disclaimers:**
176
  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).
 
5
  import pandas as pd
6
  import google.generativeai as genai
7
  import spaces
8
+ import asyncio
9
 
10
  # (Keep Constants as is)
11
  # --- Constants ---
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
+ ANSWER_CACHE = {}
14
 
15
  # --- Basic Agent Definition ---
16
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
 
41
  print(f"Error calling Gemini API: {e}")
42
  return f"Error during Gemini API call: {e}"
43
  @spaces.GPU
44
+ async def run_and_submit_all( profile: gr.OAuthProfile | None):
45
  """
46
+ Fetches all questions, runs the BasicAgent on them asynchronously,
47
+ caches the answers, submits all answers, 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
 
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 Asynchronously with Caching
95
+ async def process_question(item, agent_instance):
 
 
 
96
  task_id = item.get("task_id")
97
  question_text = item.get("question")
98
+
99
  if not task_id or question_text is None:
100
  print(f"Skipping item with missing task_id or question: {item}")
101
+ return None, None
102
+
103
+ # Check cache first
104
+ if task_id in ANSWER_CACHE:
105
+ print(f"Cache hit for task {task_id}.")
106
+ submitted_answer = ANSWER_CACHE[task_id]
107
+ log_entry = {"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer}
108
+ answer_payload = {"task_id": task_id, "submitted_answer": submitted_answer}
109
+ return log_entry, answer_payload
110
+
111
+ # If not in cache, run agent
112
  try:
113
+ print(f"Cache miss for task {task_id}. Running agent...")
114
+ # Run the synchronous agent call in a separate thread to avoid blocking the event loop
115
+ submitted_answer = await asyncio.to_thread(agent_instance, question_text)
116
+
117
+ # Cache the new answer
118
+ ANSWER_CACHE[task_id] = submitted_answer
119
+
120
+ log_entry = {"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer}
121
+ answer_payload = {"task_id": task_id, "submitted_answer": submitted_answer}
122
+ return log_entry, answer_payload
123
  except Exception as e:
124
+ print(f"Error running agent on task {task_id}: {e}")
125
+ error_message = f"AGENT ERROR: {e}"
126
+ log_entry = {"Task ID": task_id, "Question": question_text, "Submitted Answer": error_message}
127
+ # Do not create a payload for submission in case of an error
128
+ return log_entry, None
129
+
130
+ print(f"Running agent on {len(questions_data)} questions asynchronously...")
131
+ tasks = [process_question(item, agent) for item in questions_data]
132
+ results = await asyncio.gather(*tasks)
133
+
134
+ results_log = [res[0] for res in results if res and res[0] is not None]
135
+ answers_payload = [res[1] for res in results if res and res[1] is not None]
136
 
137
  if not answers_payload:
138
  print("Agent did not produce any answers to submit.")
 
193
  gr.Markdown(
194
  """
195
  **Instructions:**
 
196
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
197
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
198
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
199
  ---
200
  **Disclaimers:**
201
  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).