superone001 commited on
Commit
f8447cd
·
verified ·
1 Parent(s): d71a902

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -28
app.py CHANGED
@@ -1,37 +1,45 @@
1
- """ Basic Agent Evaluation Runner"""
2
  import os
3
- import inspect
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"
15
 
16
  # --- Basic Agent Definition ---
17
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
18
-
19
-
20
  class BasicAgent:
21
- """A langgraph agent."""
22
  def __init__(self):
23
  print("BasicAgent initialized.")
24
- self.graph = build_graph()
25
-
26
  def __call__(self, question: str) -> str:
27
  print(f"Agent received question (first 50 chars): {question[:50]}...")
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,
@@ -45,23 +53,24 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
45
  print(f"User logged in: {username}")
46
  else:
47
  print("User not logged in.")
48
- return "Please Login to Hugging Face with the button.", None
49
 
50
  api_url = DEFAULT_API_URL
51
  questions_url = f"{api_url}/questions"
52
  submit_url = f"{api_url}/submit"
53
 
54
- # 1. Instantiate Agent ( modify this part to create your agent)
55
  try:
56
  agent = BasicAgent()
57
  except Exception as e:
58
  print(f"Error instantiating agent: {e}")
59
  return f"Error initializing agent: {e}", None
60
- # 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)
 
61
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
62
  print(agent_code)
63
 
64
- # 2. Fetch Questions
65
  print(f"Fetching questions from: {questions_url}")
66
  try:
67
  response = requests.get(questions_url, timeout=15)
@@ -82,9 +91,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
82
  print(f"An unexpected error occurred fetching questions: {e}")
83
  return f"An unexpected error occurred fetching questions: {e}", None
84
 
85
- # 3. Run your Agent
86
  results_log = []
87
  answers_payload = []
 
 
 
88
  print(f"Running agent on {len(questions_data)} questions...")
89
  for item in questions_data:
90
  task_id = item.get("task_id")
@@ -93,23 +105,27 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
93
  print(f"Skipping item with missing task_id or question: {item}")
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
 
112
- # 5. Submit
113
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
114
  try:
115
  response = requests.post(submit_url, json=submission_data, timeout=60)
@@ -147,13 +163,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
147
  results_df = pd.DataFrame(results_log)
148
  return status_message, results_df
149
  except Exception as e:
150
- status_message = f"An unexpected error occurred during submission: {e}"
151
  print(status_message)
152
  results_df = pd.DataFrame(results_log)
153
  return status_message, results_df
154
 
155
 
156
- # --- Build Gradio Interface using Blocks ---
157
  with gr.Blocks() as demo:
158
  gr.Markdown("# Basic Agent Evaluation Runner")
159
  gr.Markdown(
@@ -203,5 +219,5 @@ if __name__ == "__main__":
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)
 
 
1
  import os
 
2
  import gradio as gr
3
  import requests
4
+ import inspect
5
  import pandas as pd
 
6
  from agent import build_graph
7
+ from langchain_core.messages import HumanMessage
8
+ import time
9
+ import csv
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
  # --- Basic Agent Definition ---
 
 
 
16
  class BasicAgent:
 
17
  def __init__(self):
18
  print("BasicAgent initialized.")
19
+ self.agent = build_graph()
20
+
21
  def __call__(self, question: str) -> str:
22
  print(f"Agent received question (first 50 chars): {question[:50]}...")
 
23
  messages = [HumanMessage(content=question)]
24
+ messages = self.agent.invoke({"messages": messages})
25
  answer = messages['messages'][-1].content
 
 
26
 
27
+ index = answer.find("FINAL ANSWER: ")
28
+ if index == -1:
29
+ return answer
30
+ return answer[index+14:]
31
+
32
+ # --- Upload answers solved locally ---
33
+ def csv_to_dict(file_path):
34
+ result = {}
35
+ with open(file_path, 'r') as file:
36
+ csv_reader = csv.reader(file)
37
+ header = next(csv_reader) # Skip header row
38
+ for row in csv_reader:
39
+ result[row[0]] = row[1]
40
+ return result
41
+
42
+
43
  def run_and_submit_all( profile: gr.OAuthProfile | None):
44
  """
45
  Fetches all questions, runs the BasicAgent on them, submits all answers,
 
53
  print(f"User logged in: {username}")
54
  else:
55
  print("User not logged in.")
56
+ return "Please log in to Hugging Face with the button.", None
57
 
58
  api_url = DEFAULT_API_URL
59
  questions_url = f"{api_url}/questions"
60
  submit_url = f"{api_url}/submit"
61
 
62
+ # 1. Instantiate Agent (modify this part to create your agent)
63
  try:
64
  agent = BasicAgent()
65
  except Exception as e:
66
  print(f"Error instantiating agent: {e}")
67
  return f"Error initializing agent: {e}", None
68
+
69
+ # 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)
70
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
71
  print(agent_code)
72
 
73
+ # 2. Fetch questions
74
  print(f"Fetching questions from: {questions_url}")
75
  try:
76
  response = requests.get(questions_url, timeout=15)
 
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
95
  results_log = []
96
  answers_payload = []
97
+
98
+ answers = csv_to_dict("answers.csv")
99
+
100
  print(f"Running agent on {len(questions_data)} questions...")
101
  for item in questions_data:
102
  task_id = item.get("task_id")
 
105
  print(f"Skipping item with missing task_id or question: {item}")
106
  continue
107
  try:
108
+ #submitted_answer = agent(question_text)
109
+ submitted_answer = answers[task_id]
110
+
111
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
112
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
113
+ time.sleep(10)
114
  except Exception as e:
115
+ print(f"Error running agent on task {task_id}: {e}")
116
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
117
+ time.sleep(10)
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 answers
129
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
130
  try:
131
  response = requests.post(submit_url, json=submission_data, timeout=60)
 
163
  results_df = pd.DataFrame(results_log)
164
  return status_message, results_df
165
  except Exception as e:
166
+ status_message = f"Unexpected error occurred during submission: {e}"
167
  print(status_message)
168
  results_df = pd.DataFrame(results_log)
169
  return status_message, results_df
170
 
171
 
172
+ # --- Build Gradio interface using Blocks ---
173
  with gr.Blocks() as demo:
174
  gr.Markdown("# Basic Agent Evaluation Runner")
175
  gr.Markdown(
 
219
 
220
  print("-"*(60 + len(" App Starting ")) + "\n")
221
 
222
+ print("Launching Gradio interface for Basic Agent evaluation...")
223
  demo.launch(debug=True, share=False)