Datawithsarah commited on
Commit
6ac8934
·
1 Parent(s): 781c86d

added system_prompt

Browse files
Files changed (6) hide show
  1. agent.py +84 -0
  2. app.py +24 -23
  3. fetch_questions.py +28 -0
  4. gaia_questions.csv +43 -0
  5. requirements.txt +8 -3
  6. system_prompt.txt +22 -0
agent.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langgraph.graph import StateGraph, END
2
+ from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
3
+ from langchain_core.tools import tool
4
+ from typing import TypedDict, Optional
5
+ import pandas as pd
6
+ import string
7
+
8
+ # Tools
9
+
10
+ @tool
11
+ def reverse_string(text: str) -> str:
12
+ """Reverse a string"""
13
+ return text[::-1]
14
+
15
+ @tool
16
+ def extract_numbers(text: str) -> str:
17
+ """Extract digits from a string"""
18
+ return "".join([c for c in text if c.isdigit()])
19
+
20
+ @tool
21
+ def strip_punctuation(text: str) -> str:
22
+ """Remove all punctuation from a string"""
23
+ return text.translate(str.maketrans('', '', string.punctuation))
24
+
25
+ @tool
26
+ def open_file_as_text(file_path: str) -> str:
27
+ """Open and return the contents of a text/CSV file"""
28
+ try:
29
+ with open(file_path, 'r', encoding='utf-8') as f:
30
+ return f.read()
31
+ except Exception as e:
32
+ return f"Error reading file: {e}"
33
+
34
+ @tool
35
+ def analyze_csv_file(file_path: str) -> str:
36
+ """Read CSV file and return summary of content"""
37
+ try:
38
+ df = pd.read_csv(file_path)
39
+ summary = f"Columns: {', '.join(df.columns)}\nRows: {len(df)}"
40
+ return summary
41
+ except Exception as e:
42
+ return f"CSV error: {e}"
43
+
44
+ # Agent State
45
+
46
+ class AgentState(TypedDict):
47
+ messages: list
48
+ file_name: Optional[str]
49
+
50
+ # Build Graph
51
+
52
+ def build_graph():
53
+ tools = [reverse_string, extract_numbers, strip_punctuation, open_file_as_text, analyze_csv_file]
54
+
55
+ def decide_path(state: AgentState):
56
+ if state.get("file_name"):
57
+ msg = HumanMessage(content=f"Analyze this file: {state['file_name']}")
58
+ return {"messages": state["messages"] + [msg]}
59
+ else:
60
+ return {"messages": state["messages"]}
61
+
62
+ def agent_logic(state: AgentState):
63
+ question = state["messages"][-1].content.lower()
64
+ answer = ""
65
+ if "reverse" in question:
66
+ answer = reverse_string.invoke(question)
67
+ elif "number" in question:
68
+ answer = extract_numbers.invoke(question)
69
+ elif "punctuation" in question:
70
+ answer = strip_punctuation.invoke(question)
71
+ elif state.get("file_name") and state["file_name"].endswith(".csv"):
72
+ answer = analyze_csv_file.invoke(state["file_name"])
73
+ else:
74
+ answer = "unsupported question"
75
+
76
+ return {"messages": state["messages"] + [AIMessage(content=f'final_answer("{answer}")')]}
77
+
78
+ builder = StateGraph(AgentState)
79
+ builder.add_node("router", decide_path)
80
+ builder.add_node("agent_logic", agent_logic)
81
+ builder.set_entry_point("router")
82
+ builder.set_finish_point("agent_logic")
83
+ builder.add_edge("router", "agent_logic")
84
+ return builder.compile()
app.py CHANGED
@@ -9,7 +9,6 @@ from langchain_core.messages import HumanMessage
9
  from agent import build_graph
10
 
11
 
12
-
13
  # (Keep Constants as is)
14
  # --- Constants ---
15
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -33,16 +32,15 @@ class BasicAgent:
33
  return answer[14:]
34
 
35
 
36
- def run_and_submit_all( profile: gr.OAuthProfile | None):
37
  """
38
  Fetches all questions, runs the BasicAgent on them, submits all answers,
39
  and displays the results.
40
  """
41
- # --- Determine HF Space Runtime URL and Repo URL ---
42
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
43
 
44
  if profile:
45
- username= f"{profile.username}"
46
  print(f"User logged in: {username}")
47
  else:
48
  print("User not logged in.")
@@ -52,68 +50,72 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
52
  questions_url = f"{api_url}/questions"
53
  submit_url = f"{api_url}/submit"
54
 
55
- # 1. Instantiate Agent ( modify this part to create your agent)
56
  try:
57
  agent = BasicAgent()
58
  except Exception as e:
59
  print(f"Error instantiating agent: {e}")
60
  return f"Error initializing agent: {e}", None
61
- # 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)
62
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
63
  print(agent_code)
64
 
65
- # 2. Fetch Questions
66
  print(f"Fetching questions from: {questions_url}")
67
  try:
68
  response = requests.get(questions_url, timeout=15)
69
  response.raise_for_status()
70
  questions_data = response.json()
71
  if not questions_data:
72
- print("Fetched questions list is empty.")
73
- return "Fetched questions list is empty or invalid format.", None
74
  print(f"Fetched {len(questions_data)} questions.")
75
  except requests.exceptions.RequestException as e:
76
  print(f"Error fetching questions: {e}")
77
  return f"Error fetching questions: {e}", None
78
  except requests.exceptions.JSONDecodeError as e:
79
- print(f"Error decoding JSON response from questions endpoint: {e}")
80
- print(f"Response text: {response.text[:500]}")
81
- return f"Error decoding server response for questions: {e}", None
82
  except Exception as e:
83
  print(f"An unexpected error occurred fetching questions: {e}")
84
  return f"An unexpected error occurred fetching questions: {e}", None
85
 
86
- # 3. Run your Agent
87
  results_log = []
88
  answers_payload = []
89
  print(f"Running agent on {len(questions_data)} questions...")
 
 
 
 
90
  for item in questions_data:
91
  task_id = item.get("task_id")
92
  question_text = item.get("question")
 
 
93
  if not task_id or question_text is None:
94
  print(f"Skipping item with missing task_id or question: {item}")
95
  continue
96
-
97
- # time.sleep(10)
98
-
99
  try:
100
- submitted_answer = agent(question_text)
 
 
 
 
 
101
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
102
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
103
  except Exception as e:
104
- print(f"Error running agent on task {task_id}: {e}")
105
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
106
 
107
  if not answers_payload:
108
  print("Agent did not produce any answers to submit.")
109
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
110
 
111
- # 4. Prepare Submission
112
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
113
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
114
  print(status_update)
115
 
116
- # 5. Submit
117
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
118
  try:
119
  response = requests.post(submit_url, json=submission_data, timeout=60)
@@ -156,7 +158,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
156
  results_df = pd.DataFrame(results_log)
157
  return status_message, results_df
158
 
159
-
160
  # --- Build Gradio Interface using Blocks ---
161
  with gr.Blocks() as demo:
162
  gr.Markdown("# Basic Agent Evaluation Runner")
 
9
  from agent import build_graph
10
 
11
 
 
12
  # (Keep Constants as is)
13
  # --- Constants ---
14
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
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,
38
  and displays the results.
39
  """
40
+ space_id = os.getenv("SPACE_ID")
 
41
 
42
  if profile:
43
+ username = f"{profile.username}"
44
  print(f"User logged in: {username}")
45
  else:
46
  print("User not logged in.")
 
50
  questions_url = f"{api_url}/questions"
51
  submit_url = f"{api_url}/submit"
52
 
 
53
  try:
54
  agent = BasicAgent()
55
  except Exception as e:
56
  print(f"Error instantiating agent: {e}")
57
  return f"Error initializing agent: {e}", None
58
+
59
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
60
  print(agent_code)
61
 
 
62
  print(f"Fetching questions from: {questions_url}")
63
  try:
64
  response = requests.get(questions_url, timeout=15)
65
  response.raise_for_status()
66
  questions_data = response.json()
67
  if not questions_data:
68
+ print("Fetched questions list is empty.")
69
+ return "Fetched questions list is empty or invalid format.", None
70
  print(f"Fetched {len(questions_data)} questions.")
71
  except requests.exceptions.RequestException as e:
72
  print(f"Error fetching questions: {e}")
73
  return f"Error fetching questions: {e}", None
74
  except requests.exceptions.JSONDecodeError as e:
75
+ print(f"Error decoding JSON response from questions endpoint: {e}")
76
+ print(f"Response text: {response.text[:500]}")
77
+ return f"Error decoding server response for questions: {e}", None
78
  except Exception as e:
79
  print(f"An unexpected error occurred fetching questions: {e}")
80
  return f"An unexpected error occurred fetching questions: {e}", None
81
 
 
82
  results_log = []
83
  answers_payload = []
84
  print(f"Running agent on {len(questions_data)} questions...")
85
+
86
+ with open("system_prompt.txt", "r", encoding="utf-8") as f:
87
+ system_prompt = f.read().strip()
88
+
89
  for item in questions_data:
90
  task_id = item.get("task_id")
91
  question_text = item.get("question")
92
+ file_name = item.get("file_name")
93
+
94
  if not task_id or question_text is None:
95
  print(f"Skipping item with missing task_id or question: {item}")
96
  continue
97
+
 
 
98
  try:
99
+ user_message = question_text
100
+ if file_name:
101
+ user_message += f"\n\nFile to use: {file_name}"
102
+
103
+ print(f"Running agent on task {task_id}...")
104
+ submitted_answer = agent(system_prompt + "\n\n" + user_message)
105
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
106
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
107
  except Exception as e:
108
+ print(f"Error running agent on task {task_id}: {e}")
109
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
110
 
111
  if not answers_payload:
112
  print("Agent did not produce any answers to submit.")
113
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
114
 
 
115
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
116
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
117
  print(status_update)
118
 
 
119
  print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
120
  try:
121
  response = requests.post(submit_url, json=submission_data, timeout=60)
 
158
  results_df = pd.DataFrame(results_log)
159
  return status_message, results_df
160
 
 
161
  # --- Build Gradio Interface using Blocks ---
162
  with gr.Blocks() as demo:
163
  gr.Markdown("# Basic Agent Evaluation Runner")
fetch_questions.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import pandas as pd
3
+
4
+ API_URL = "https://agents-course-unit4-scoring.hf.space/questions"
5
+
6
+ def fetch_and_print_questions():
7
+ try:
8
+ response = requests.get(API_URL, timeout=10)
9
+ response.raise_for_status()
10
+ questions = response.json()
11
+
12
+ print(f" Retrieved {len(questions)} questions:\n")
13
+ for q in questions:
14
+ task_id = q.get("task_id")
15
+ text = q.get("question")
16
+ print(f"[{task_id}] {text}")
17
+
18
+ # Save to CSV
19
+ df = pd.DataFrame(questions)
20
+ df.to_csv("gaia_questions.csv", index=False)
21
+ print("\n Questions saved to gaia_questions.csv")
22
+
23
+ except Exception as e:
24
+ print(f" Failed to fetch questions: {e}")
25
+
26
+ # Run this once manually (outside of Gradio)
27
+ if __name__ == "__main__":
28
+ fetch_and_print_questions()
gaia_questions.csv ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ task_id,question,Level,file_name
2
+ 8e867cd7-cff9-4e6c-867a-ff5ddc2550be,How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.,1,
3
+ a1e91b78-d3d8-4675-bb8d-62741b4b68a6,"In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?",1,
4
+ 2d83110e-a098-4ebb-9987-066c06fa42d0,".rewsna eht sa ""tfel"" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI",1,
5
+ cca530fc-4052-43b2-b130-b30968d8aa44,Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.,1,cca530fc-4052-43b2-b130-b30968d8aa44.png
6
+ 4fc2f1ae-8625-45b5-ab34-ad4433bc21f8,Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?,1,
7
+ 6f37996b-2ac7-44b0-8e68-6d28256631b4,"Given this table defining * on the set S = {a, b, c, d, e}
8
+
9
+ |*|a|b|c|d|e|
10
+ |---|---|---|---|---|---|
11
+ |a|a|b|c|b|d|
12
+ |b|b|c|a|e|c|
13
+ |c|c|a|b|b|a|
14
+ |d|b|e|b|e|d|
15
+ |e|d|b|a|d|c|
16
+
17
+ provide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.",1,
18
+ 9d191bce-651d-4746-be2d-7ef8ecadb9c2,"Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.
19
+
20
+ What does Teal'c say in response to the question ""Isn't that hot?""",1,
21
+ cabe07ed-9eca-40ea-8ead-410ef5e83f91,What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?,1,
22
+ 3cef3a44-215e-4aed-8e3b-b1e3f08063b7,"I'm making a grocery list for my mom, but she's a professor of botany and she's a real stickler when it comes to categorizing things. I need to add different foods to different categories on the grocery list, but if I make a mistake, she won't buy anything inserted in the wrong category. Here's the list I have so far:
23
+
24
+ milk, eggs, flour, whole bean coffee, Oreos, sweet potatoes, fresh basil, plums, green beans, rice, corn, bell pepper, whole allspice, acorns, broccoli, celery, zucchini, lettuce, peanuts
25
+
26
+ I need to make headings for the fruits and vegetables. Could you please create a list of just the vegetables from my list? If you could do that, then I can figure out how to categorize the rest of the list into the appropriate categories. But remember that my mom is a real stickler, so make sure that no botanical fruits end up on the vegetable list, or she won't get them when she's at the store. Please alphabetize the list of vegetables, and place each item in a comma separated list.",1,
27
+ 99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3,"Hi, I'm making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I'm not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.
28
+
29
+ In your response, please only list the ingredients, not any measurements. So if the recipe calls for ""a pinch of salt"" or ""two cups of ripe strawberries"" the ingredients on the list would be ""salt"" and ""ripe strawberries"".
30
+
31
+ Please format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",1,99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3
32
+ 305ac316-eef6-4446-960a-92d80d542f82,Who did the actor who played Ray in the Polish-language version of Everybody Loves Raymond play in Magda M.? Give only the first name.,1,
33
+ f918266a-b3e0-4914-865d-4faa564f1aef,What is the final numeric output from the attached Python code?,1,f918266a-b3e0-4914-865d-4faa564f1aef.py
34
+ 3f57289b-8c60-48be-bd80-01f8099ca449,How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?,1,
35
+ 1f975693-876d-457b-a649-393859e79bf3,"Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(
36
+
37
+ Could you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",1,1f975693-876d-457b-a649-393859e79bf3.mp3
38
+ 840bfca7-4f7b-481a-8794-c560c340185d,"On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?",1,
39
+ bda648d7-d618-4883-88f4-3466eabd860e,Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.,1,
40
+ cf106601-ab4f-4af9-b045-5295fe67b37d,"What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer.",1,
41
+ a0c07678-e491-4bbc-8f0b-07405144218f,"Who are the pitchers with the number before and after Taishō Tamai's number as of July 2023? Give them to me in the form Pitcher Before, Pitcher After, use their last names only, in Roman characters.",1,
42
+ 7bd855d8-463d-4ed5-93ca-5fe35145f733,The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.,1,7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx
43
+ 5a0c1adf-205e-4841-a666-7c3ef95def9d,What is the first name of the only Malko Competition recipient from the 20th Century (after 1977) whose nationality on record is a country that no longer exists?,1,
requirements.txt CHANGED
@@ -1,5 +1,10 @@
1
- langgraph
2
- langchain-core
3
  gradio
4
  pandas
5
- requests
 
 
 
 
 
 
 
 
 
 
1
  gradio
2
  pandas
3
+ requests
4
+ langchain-core
5
+ langgraph
6
+ langchain
7
+ langchain-community
8
+ huggingface-hub
9
+ python-dotenv
10
+ tqdm
system_prompt.txt ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a highly focused AI assistant participating in the GAIA benchmark challenge.
2
+
3
+ Your goal is to answer each question precisely, using tools when necessary. Follow these rules strictly:
4
+
5
+ - NEVER output explanations, reasoning, or intermediate thoughts.
6
+ - NEVER output more than one answer.
7
+ - When you reach the final answer, return it as:
8
+ final_answer("...your answer...")
9
+ - Use tools like `open_file_as_text`, `extract_number`, or `reverse_text` where applicable.
10
+ - If the task involves a file, use the given file_name — not one mentioned in the question.
11
+ - Format numbers without commas or symbols (e.g., 1739, not $1,739).
12
+ - Format comma-separated lists with a single space after each comma.
13
+ - When extracting or reversing text, always preserve punctuation unless instructed otherwise.
14
+
15
+ Example:
16
+ Q: What is the reverse of "good job"?
17
+ A: final_answer("boj doog")
18
+
19
+ Q: What is the third number listed in the attached file?
20
+ A: final_answer("42")
21
+
22
+ Be brief. Be exact. Use tools. Output only the final answer in the correct format.