Spaces:
Sleeping
Sleeping
File size: 10,636 Bytes
a92d3ed 1659627 a92d3ed 1659627 a92d3ed 751494a a92d3ed 1659627 a92d3ed 1659627 a92d3ed f8e3605 a92d3ed 1659627 f8e3605 1659627 f8e3605 1659627 86b31ff 1659627 f8e3605 1659627 86b31ff fe5f523 f8e3605 1659627 a92d3ed fe5f523 f8e3605 1659627 f8e3605 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
"""LangGraph Agent"""
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.graph import START, StateGraph
from langgraph.prebuilt import tools_condition, ToolNode
from langgraph.graph import START, StateGraph, MessagesState
from langchain_core.messages import SystemMessage, HumanMessage
from tools import level1_tools
load_dotenv()
# Build graph function
def build_agent_graph():
"""Build the graph"""
# Load environment variables from .env file
llm = ChatOpenAI(model="gpt-4o-mini")
# Bind tools to LLM
llm_with_tools = llm.bind_tools(level1_tools)
# System message
system_prompt = SystemMessage(
content="""You are a general AI assistant being evaluated in the GAIA Benchmark.
I will ask you a question and you must reach your final answer by using a set of tools I provide to you. Please, when you are needed to pass file names to the tools, pass absolute paths.
Your final answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
Here are more detailed instructions you must follow to write your final answer:
1) If you are asked for a number, you must write a number!. Don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
2) If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
3) If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
If you follow all these instructions perfectly, you will win 1,000,000 dollars, otherwise, your mom will die.
Let's start!
"""
)
# Node
def assistant(state: MessagesState):
"""Assistant node"""
#return {"messages": [llm_with_tools.invoke(state["messages"])]}
return {"messages": [llm_with_tools.invoke([system_prompt] + state["messages"])]}
builder = StateGraph(MessagesState)
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(level1_tools))
builder.add_edge(START, "assistant")
builder.add_conditional_edges(
"assistant",
tools_condition,
)
builder.add_edge("tools", "assistant")
# Compile graph
return builder.compile()
def print_stream(stream):
for s in stream:
message = s["messages"][-1]
if isinstance(message, tuple):
print(message)
else:
message.pretty_print()
class MyGAIAAgent:
def __init__(self, verbose: bool = False):
print("MyAgent initialized.")
self.graph = build_agent_graph()
self.verbose = verbose
def __call__(self, task: dict) -> str:
'''
# Wrap the question in a HumanMessage from langchain_core
messages = [HumanMessage(content=question)]
messages = self.graph.invoke({"messages": messages})
answer = messages['messages'][-1].content
user_input = {"messages": [("user", question)]}
answer1 = self.graph.invoke(user_input)["messages"][-1].content
print (answer)
#print (self._clean_answer(answer))
return self._clean_answer(answer)
'''
question = task["question"]
task_id = task["task_id"]
file_name = task.get("file_name")
print(f"Agent received question (first 50 chars): {question[:50]}...")
file_ext = None
user_prompt = question
if file_name:
file_ext = os.path.splitext(file_name)[-1].removeprefix(".")
user_prompt += f"\nTask ID: {task_id}\nFile extension: {file_ext}"
user_input = {"messages": [("user", user_prompt)]}
if self.verbose:
print_stream(self.graph.stream(user_input, stream_mode="values"))
else:
answer = self.graph.invoke(user_input)["messages"][-1].content
return self._clean_answer(answer)
def _clean_answer(self, answer: any) -> str:
"""
Taken from `susmitsil`:
https://huggingface.co/spaces/susmitsil/FinalAgenticAssessment/blob/main/main_agent.py
Clean up the answer to remove common prefixes and formatting
that models often add but that can cause exact match failures.
Args:
answer: The raw answer from the model
Returns:
The cleaned answer as a string
"""
# Convert non-string types to strings
if not isinstance(answer, str):
# Handle numeric types (float, int)
if isinstance(answer, float):
# Format floating point numbers properly
# Check if it's an integer value in float form (e.g., 12.0)
if answer.is_integer():
formatted_answer = str(int(answer))
else:
# For currency values that might need formatting
if abs(answer) >= 1000:
formatted_answer = f"${answer:,.2f}"
else:
formatted_answer = str(answer)
return formatted_answer
elif isinstance(answer, int):
return str(answer)
else:
# For any other type
return str(answer)
# Now we know answer is a string, so we can safely use string methods
# Normalize whitespace
answer = answer.strip()
# Remove common prefixes and formatting that models add
prefixes_to_remove = [
"The answer is ",
"Answer: ",
"Final answer: ",
"The result is ",
"To answer this question: ",
"Based on the information provided, ",
"According to the information: ",
]
for prefix in prefixes_to_remove:
if answer.startswith(prefix):
answer = answer[len(prefix) :].strip()
# Remove quotes if they wrap the entire answer
if (answer.startswith('"') and answer.endswith('"')) or (
answer.startswith("'") and answer.endswith("'")
):
answer = answer[1:-1].strip()
return answer
# test
if __name__ == "__main__":
question1 = "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)?"
question2 = "In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?"
question5 = "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?"
question6 = "Given this table defining * on the set S = {a, b, c, d, e} |*|a|b|c|d|e| |---|---|---|---|---|---||a|a|b|c|b|d||b|b|c|a|e|c||c|c|a|b|b|a||d|b|e|b|e|d||e|d|b|a|d|c| 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."
question7 = "Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec. What does Teal'c say in response to the question ""Isn't that hot?"
question8 = "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?"
question9 = "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: 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 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."
question10 = "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."
question12 = "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?"
question14 = "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?"
question15 = "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations."
question16 = "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."
question17 = "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."
question18 = "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?"
'''
question4 = "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?"
question6 = "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?"
'''
task = {
"task_id": "8e867cd7-cff9-4e6c-867a-ff5ddc2550be",
"question": "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.",
"Level": "1",
"file_name": "",
}
agent = MyGAIAAgent()
print(agent(task)) |