22Nikk0 commited on
Commit
03444e7
·
verified ·
1 Parent(s): f185618

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -44
app.py CHANGED
@@ -11,14 +11,35 @@ 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 run_and_submit_all( profile: gr.OAuthProfile | None):
24
  """
@@ -26,7 +47,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
26
  and displays the results.
27
  """
28
  # --- Determine HF Space Runtime URL and Repo URL ---
29
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
30
 
31
  if profile:
32
  username= f"{profile.username}"
@@ -37,28 +58,35 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
37
 
38
  api_url = DEFAULT_API_URL
39
  questions_url = f"{api_url}/questions"
 
40
  submit_url = f"{api_url}/submit"
41
 
42
  # 1. Instantiate Agent ( modify this part to create your agent)
43
- # try:
44
- # agent = BasicAgent()
45
- # except Exception as e:
46
- # print(f"Error instantiating agent: {e}")
47
- # return f"Error initializing agent: {e}", None
48
- # # 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)
49
- # agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
50
- # print(agent_code)
51
 
52
  # 2. Fetch Questions
53
- print(f"Fetching questions from: {questions_url}")
 
54
  try:
55
- response = requests.get(questions_url, timeout=15)
 
56
  response.raise_for_status()
57
  questions_data = response.json()
58
  if not questions_data:
59
  print("Fetched questions list is empty.")
60
  return "Fetched questions list is empty or invalid format.", None
61
- print(f"Fetched {len(questions_data)} questions.")
 
 
 
 
62
  except requests.exceptions.RequestException as e:
63
  print(f"Error fetching questions: {e}")
64
  return f"Error fetching questions: {e}", None
@@ -70,36 +98,32 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
70
  print(f"An unexpected error occurred fetching questions: {e}")
71
  return f"An unexpected error occurred fetching questions: {e}", None
72
 
73
- print(questions_data)
74
-
75
- return None, None
76
-
77
  # 3. Run your Agent
78
- # results_log = []
79
- # answers_payload = []
80
- # print(f"Running agent on {len(questions_data)} questions...")
81
- # for item in questions_data:
82
- # task_id = item.get("task_id")
83
- # question_text = item.get("question")
84
- # if not task_id or question_text is None:
85
- # print(f"Skipping item with missing task_id or question: {item}")
86
- # continue
87
- # try:
88
- # submitted_answer = agent(question_text)
89
- # answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
90
- # results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
91
- # except Exception as e:
92
- # print(f"Error running agent on task {task_id}: {e}")
93
- # results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
94
-
95
- # if not answers_payload:
96
- # print("Agent did not produce any answers to submit.")
97
- # return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
98
-
99
- # # 4. Prepare Submission
100
- # submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
101
- # status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
102
- # print(status_update)
103
 
104
  # # 5. Submit
105
  # print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
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
  class BasicAgent:
23
  def __init__(self):
24
  print("BasicAgent initialized.")
25
+ self.agent_graph = build_graph()
26
  def __call__(self, question: str) -> str:
27
  print(f"Agent received question (first 50 chars): {question[:50]}...")
28
+ # fixed_answer = "This is a default answer."
29
+ # print(f"Agent returning fixed answer: {fixed_answer}")
30
+ # return fixed_answer
31
+ messages = [HumanMessage(content=f"Can you answer this question please ? {question}")]
32
+
33
+ messages = self.agent_graph.invoke({"messages": messages, "question": question}, {"recursion_limit": 10})
34
+
35
+ try:
36
+ regex_result = re.search(r"FINAL ANSWER:\s*(?P<answer>.*)$", messages['messages'][-1].content)
37
+ answer = regex_result.group("answer")
38
+ except:
39
+ regex_result = re.search(r"\s*(?P<answer>.*)$", messages['messages'][-1].content)
40
+ answer = regex_result.group("answer")
41
+
42
+ return answer
43
 
44
  def run_and_submit_all( profile: gr.OAuthProfile | None):
45
  """
 
47
  and displays the results.
48
  """
49
  # --- Determine HF Space Runtime URL and Repo URL ---
50
+ space_id = os.getenv("SPACE_ID", "local") # Get the SPACE_ID for sending link to the code
51
 
52
  if profile:
53
  username= f"{profile.username}"
 
58
 
59
  api_url = DEFAULT_API_URL
60
  questions_url = f"{api_url}/questions"
61
+ one_question_url = f"{api_url}/random-question"
62
  submit_url = f"{api_url}/submit"
63
 
64
  # 1. Instantiate Agent ( modify this part to create your agent)
65
+ try:
66
+ agent = BasicAgent()
67
+ except Exception as e:
68
+ print(f"Error instantiating agent: {e}")
69
+ return f"Error initializing agent: {e}", None
70
+ # 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)
71
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
72
+ print(agent_code)
73
 
74
  # 2. Fetch Questions
75
+ # print(f"Fetching questions from: {questions_url}")
76
+ print(f"Fetching questions from: {one_question_url}")
77
  try:
78
+ # response = requests.get(questions_url, timeout=15)
79
+ response = requests.get(one_question_url, timeout=15)
80
  response.raise_for_status()
81
  questions_data = response.json()
82
  if not questions_data:
83
  print("Fetched questions list is empty.")
84
  return "Fetched questions list is empty or invalid format.", None
85
+ if isinstance(questions_data, dict) and "question" in questions_data:
86
+ print("Fetched a single question instead of a list.")
87
+ questions_data = [questions_data]
88
+ elif isinstance(questions_data, list):
89
+ print(f"Fetched {len(questions_data)} questions.")
90
  except requests.exceptions.RequestException as e:
91
  print(f"Error fetching questions: {e}")
92
  return f"Error fetching questions: {e}", None
 
98
  print(f"An unexpected error occurred fetching questions: {e}")
99
  return f"An unexpected error occurred fetching questions: {e}", None
100
 
 
 
 
 
101
  # 3. Run your Agent
102
+ results_log = []
103
+ answers_payload = []
104
+ print(f"Running agent on {len(questions_data)} questions...")
105
+ for item in questions_data:
106
+ task_id = item.get("task_id")
107
+ question_text = item.get("question")
108
+ if not task_id or question_text is None:
109
+ print(f"Skipping item with missing task_id or question: {item}")
110
+ continue
111
+ try:
112
+ submitted_answer = agent(question_text)
113
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
114
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
115
+ except Exception as e:
116
+ print(f"Error running agent on task {task_id}: {e}")
117
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
118
+
119
+ if not answers_payload:
120
+ print("Agent did not produce any answers to submit.")
121
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
122
+
123
+ # 4. Prepare Submission
124
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
125
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
126
+ print(status_update)
127
 
128
  # # 5. Submit
129
  # print(f"Submitting {len(answers_payload)} answers to: {submit_url}")