cpatino10 commited on
Commit
7e61f1a
·
verified ·
1 Parent(s): 4627666

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -17
app.py CHANGED
@@ -3,22 +3,24 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
6
  from agent import run_agent
7
 
8
  # (Keep Constants as is)
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
11
 
12
  # --- Basic Agent Definition ---
13
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
14
  class BasicAgent:
15
  def __init__(self):
16
  print("BasicAgent initialized.")
 
17
  def __call__(self, question: str) -> str:
18
  print(f"Agent received question (first 50 chars): {question[:50]}...")
19
- fixed_answer = "This is a default answer."
20
- print(f"Agent returning fixed answer: {fixed_answer}")
21
- return fixed_answer
22
 
23
  def download_task_file(task_id: str, save_dir: str = "downloads"):
24
  os.makedirs(save_dir, exist_ok=True)
@@ -43,6 +45,20 @@ def download_task_file(task_id: str, save_dir: str = "downloads"):
43
 
44
  return None
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  def run_and_submit_all( profile: gr.OAuthProfile | None):
47
  """
48
  Fetches all questions, runs the BasicAgent on them, submits all answers,
@@ -62,6 +78,9 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
62
  questions_url = f"{api_url}/questions"
63
  submit_url = f"{api_url}/submit"
64
 
 
 
 
65
  # 1. Instantiate Agent ( modify this part to create your agent)
66
  try:
67
  agent = BasicAgent()
@@ -96,30 +115,53 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
96
  # 3. Run your Agent
97
  results_log = []
98
  answers_payload = []
 
99
  print(f"Running agent on {len(questions_data)} questions...")
 
100
  for item in questions_data:
101
  task_id = item.get("task_id")
102
  question_text = item.get("question")
 
 
103
 
104
  if not task_id or question_text is None:
105
  print(f"Skipping item with missing task_id or question: {item}")
106
  continue
107
- try:
108
- # try to download the file
109
- file_path = download_task_file(task_id)
110
 
111
- if file_path:
112
- full_prompt = f"{question_text}\n\n[IMPORTANT] A file associated with this task is located at: {file_path}. Use your tools to read it if necessary."
113
- else:
114
- full_prompt = question_text
115
-
116
- submitted_answer = run_agent(full_prompt)
117
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
118
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
119
- except Exception as e:
120
- print(f"Error running agent on task {task_id}: {e}")
121
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
 
 
 
 
 
 
 
 
123
  if not answers_payload:
124
  print("Agent did not produce any answers to submit.")
125
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ import json
7
  from agent import run_agent
8
 
9
  # (Keep Constants as is)
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
+ CACHE_FILE = "answers_cache.json"
13
 
14
  # --- Basic Agent Definition ---
15
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
16
  class BasicAgent:
17
  def __init__(self):
18
  print("BasicAgent initialized.")
19
+
20
  def __call__(self, question: str) -> str:
21
  print(f"Agent received question (first 50 chars): {question[:50]}...")
22
+
23
+ return run_agent(question)
 
24
 
25
  def download_task_file(task_id: str, save_dir: str = "downloads"):
26
  os.makedirs(save_dir, exist_ok=True)
 
45
 
46
  return None
47
 
48
+ # --- Cache helper ---
49
+ def load_cache():
50
+ if os.path.exists(CACHE_FILE):
51
+ try:
52
+ with open(CACHE_FILE, "r") as f:
53
+ return json.load(f)
54
+ except Exception:
55
+ return {}
56
+ return {}
57
+
58
+ def save_cache(cache_data):
59
+ with open(CACHE_FILE, "w") as f:
60
+ json.dump(cache_data, f, indent=4)
61
+
62
  def run_and_submit_all( profile: gr.OAuthProfile | None):
63
  """
64
  Fetches all questions, runs the BasicAgent on them, submits all answers,
 
78
  questions_url = f"{api_url}/questions"
79
  submit_url = f"{api_url}/submit"
80
 
81
+ # load existing progress
82
+ answer_cache = load_cache()
83
+ print(f"Loaded {len(answer_cache)} answers from cache")
84
  # 1. Instantiate Agent ( modify this part to create your agent)
85
  try:
86
  agent = BasicAgent()
 
115
  # 3. Run your Agent
116
  results_log = []
117
  answers_payload = []
118
+
119
  print(f"Running agent on {len(questions_data)} questions...")
120
+
121
  for item in questions_data:
122
  task_id = item.get("task_id")
123
  question_text = item.get("question")
124
+
125
+ submitted_answer = "NO answer generated"
126
 
127
  if not task_id or question_text is None:
128
  print(f"Skipping item with missing task_id or question: {item}")
129
  continue
 
 
 
130
 
131
+ # check cache
132
+ if task_id in answer_cache:
133
+ print(f"Task {task_id} found in cache. Skipping generation")
134
+ submitted_answer = answer_cache[task_id]
135
+ else:
136
+ print(f"Task {task_id} not in cache. Running agent...")
137
+ try:
138
+ # try to download the file
139
+ file_path = download_task_file(task_id)
140
+
141
+ if file_path:
142
+ full_prompt = f"{question_text}\n\n[IMPORTANT] A file associated with this task is located at: {file_path}. Use your tools to read it if necessary."
143
+ else:
144
+ full_prompt = question_text
145
+
146
+ submitted_answer = run_agent(full_prompt)
147
+
148
+ # update cache
149
+ answer_cache[task_id] = submitted_answer
150
+ save_cache(answer_cache)
151
+
152
+
153
+ except Exception as e:
154
+ print(f"Error running agent on task {task_id}: {e}")
155
+ submitted_answer = f"AGENT ERROR: {e}"
156
 
157
+ # add to payload
158
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
159
+ results_log.append({
160
+ "Task ID": task_id,
161
+ "Question": question_text,
162
+ "Submitted Answer": submitted_answer,
163
+ "Source": "Cache" if task_id in answer_cache else "New Run"
164
+ })
165
  if not answers_payload:
166
  print("Agent did not produce any answers to submit.")
167
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)