fhueni commited on
Commit
ab8fe52
·
1 Parent(s): 81917a3

feat: implement agent with smolagents and add caching of answers and results

Browse files
Files changed (3) hide show
  1. README.md +1 -1
  2. app.py +43 -12
  3. src/agent.py +27 -0
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Template Final Assignment
3
  emoji: 🕵🏻‍♂️
4
  colorFrom: indigo
5
  colorTo: indigo
 
1
  ---
2
+ title: HF Agent Course Final Assignment
3
  emoji: 🕵🏻‍♂️
4
  colorFrom: indigo
5
  colorTo: indigo
app.py CHANGED
@@ -3,21 +3,15 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
14
- def __init__(self):
15
- print("BasicAgent initialized.")
16
- def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
@@ -28,7 +22,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
28
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
 
30
  if profile:
31
- username= f"{profile.username}"
32
  print(f"User logged in: {username}")
33
  else:
34
  print("User not logged in.")
@@ -69,16 +63,45 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
69
  print(f"An unexpected error occurred fetching questions: {e}")
70
  return f"An unexpected error occurred fetching questions: {e}", None
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  # 3. Run your Agent
73
  results_log = []
74
  answers_payload = []
 
 
 
 
 
 
 
75
  print(f"Running agent on {len(questions_data)} questions...")
76
- for item in questions_data:
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
79
  if not task_id or question_text is None:
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
 
 
 
82
  try:
83
  submitted_answer = agent(question_text)
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
@@ -91,6 +114,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
91
  print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
 
 
 
 
 
 
 
 
94
  # 4. Prepare Submission
95
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from dotenv import load_dotenv
7
+ from src.agent import BasicAgent
8
+
9
+ load_dotenv()
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  def run_and_submit_all( profile: gr.OAuthProfile | None):
17
  """
 
22
  space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
23
 
24
  if profile:
25
+ username = f"{profile.username}"
26
  print(f"User logged in: {username}")
27
  else:
28
  print("User not logged in.")
 
63
  print(f"An unexpected error occurred fetching questions: {e}")
64
  return f"An unexpected error occurred fetching questions: {e}", None
65
 
66
+ # 2.1 Load cached results if available
67
+ cached_results = None
68
+ cached_answers = None
69
+ if os.path.exists("cached_results.csv"):
70
+ try:
71
+ cached_results = pd.read_csv("cached_results.csv")
72
+ print(f"Loaded cached results from cached_results.csv with {len(cached_results)} entries.")
73
+ except Exception as e:
74
+ print(f"Error loading cached results: {e}")
75
+ return f"Error loading cached results: {e}", None
76
+
77
+ if os.path.exists("cached_answers.csv"):
78
+ try:
79
+ cached_answers = pd.read_csv("cached_answers.csv")
80
+ print(f"Loaded cached answers from cached_answers.csv with {len(cached_answers)} entries.")
81
+ except Exception as e:
82
+ print(f"Error loading cached answers: {e}")
83
+ return f"Error loading cached answers: {e}", None
84
+
85
  # 3. Run your Agent
86
  results_log = []
87
  answers_payload = []
88
+
89
+ # If cached results or answers are available, append them to the log
90
+ if cached_results is not None:
91
+ results_log = cached_results.to_dict(orient="records")
92
+ if cached_answers is not None:
93
+ answers_payload = cached_answers.to_dict(orient="records")
94
+
95
  print(f"Running agent on {len(questions_data)} questions...")
96
+ for item in questions_data[0:20]:
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
+ if not cached_answers.empty and any(d['task_id'] == task_id for d in answers_payload):
103
+ print(f"Skipping task {task_id} as it is already answered in cached answers.")
104
+ continue
105
  try:
106
  submitted_answer = agent(question_text)
107
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
 
114
  print("Agent did not produce any answers to submit.")
115
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
116
 
117
+ # 3.1 Store results to file system
118
+ results_df = pd.DataFrame(results_log)
119
+ results_df.to_csv("cached_results.csv", index=False)
120
+
121
+ answers_df = pd.DataFrame(answers_payload)
122
+ answers_df.to_csv("cached_answers.csv", index=False)
123
+ print("Results saved to file system")
124
+
125
  # 4. Prepare Submission
126
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
127
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
src/agent.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import yaml
4
+ from smolagents import OpenAIServerModel, CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool
5
+
6
+
7
+ model = OpenAIServerModel(
8
+ model_id="claude-3-5-haiku-20241022",
9
+ api_base="https://api.anthropic.com/v1/",
10
+ api_key=os.environ["ANTROPHIC_API_KEY"],
11
+ )
12
+
13
+ agent = CodeAgent(
14
+ model=model,
15
+ tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
16
+ max_steps=10,
17
+ additional_authorized_imports=["time", "numpy", "pandas"]
18
+ )
19
+
20
+ class BasicAgent:
21
+ def __init__(self):
22
+ print("BasicAgent initialized.")
23
+ def __call__(self, question: str) -> str:
24
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
25
+ answer = agent.run(question)
26
+ print(f"Agent returning answer: {answer}")
27
+ return answer