su3su2u1's picture
update
b5d40a7 unverified
import json
import os
import pandas as pd
from PIL import Image
from smolagents import (
CodeAgent,
ToolCallingAgent,
# HfApiModel,
DuckDuckGoSearchTool,
PythonInterpreterTool,
VisitWebpageTool,
OpenAIServerModel,
Tool,
)
from tools import EnglishSpeechToTextTool
cache = {
"How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.": "4", # wrong, should be 3
"In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?": "7234", # wrong
'.rewsna eht sa "tfel" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI': "right", # correct
"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.": None, # wrong
"Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?": "FunkMonk", # correct
"""Given this table defining * on the set S = {a, b, c, d, e}""": "b, e", # correct
"Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.": "Extremely", # correct
"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?": "Louvrier", # correct
"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:": "wrong", # wrong
"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.": "wrong", # wrong
"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.": "Wojciech", # correct
"What is the final numeric output from the attached Python code?": "0", # correct
"How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?": "519", # correct
"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 :(": "wrong", # wrong
"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?": "80GSFC21M0002", # correct
"Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.": "Saint Petersburg", # correct, but not always
"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.": "CUB", # correct
"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.": "wrong", # wrong
"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.": "89706.00", # wrong
"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?": "Claus", # correct
}
class ExecutePythonTool(Tool):
name = "python_executor"
description = "This is a tool that executes a python file."
output_type = "string"
def __init__(self, *args, authorized_imports=None, **kwargs):
# self.python_interpreter = PythonInterpreterTool()
self.inputs = {
"file_path": {
"type": "string",
"description": "The python file path to be executed",
}
}
super().__init__(*args, **kwargs)
def forward(self, file_path: str) -> str:
# with open(file_path) as f:
# code = f.read()
# sucks because it can't interpret class x: pass
# return self.python_interpreter.forward(code)
import subprocess
output = subprocess.check_output(["python3", file_path])
return output
class BasicAgent:
def __init__(self):
# model = HfApiModel("Qwen/Qwen2.5-Coder-32B-Instruct")
# OpenAI; gpt-4o-mini is far worse than gemini-2.0-flash
if 0:
model = OpenAIServerModel(
model_id="gpt-4o-mini",
# model_id="o3-mini",
api_base="https://api.openai.com/v1",
api_key=os.getenv("OPENAI_API_TOKEN"),
# temperature=0,
)
# Gemini
model = OpenAIServerModel(
# model_id="gemini-2.5-flash-preview-04-17",
model_id="gemini-2.0-flash",
api_base="https://generativelanguage.googleapis.com/v1beta/openai/",
api_key=os.getenv("GEMINI_API_TOKEN"),
# reasoning_effort="low", # Only for 2.5
# temperature=0,
)
model25 = OpenAIServerModel(
model_id="gemini-2.5-flash-preview-04-17",
api_base="https://generativelanguage.googleapis.com/v1beta/openai/",
api_key=os.getenv("GEMINI_API_TOKEN"),
reasoning_effort="low", # Only for 2.5
# temperature=0,
)
web_agent = ToolCallingAgent(
tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],
model=model,
max_steps=5,
name="search",
description="Runs web searches for you. Give it your query as an argument.",
)
chess_analyzer_agent = ToolCallingAgent(
tools=[],
model=model25,
max_steps=3,
name="analyze_chess_position",
description="Analyze a given chess position for best one move to checkmate. Give it the board (included in `task` argument) in algebraic notation",
)
chess_analyzer_agent.prompt_templates["system_prompt"] = (
"You are an expert chess puzzle solver. You will be given a chess puzzle in algebraic notation, that you have to provide the step to checkmate. You also have to answer in algebraic notation."
)
excel_summarizer_agent = CodeAgent(
tools=[],
model=model,
max_steps=3,
name="summarize_excel_sheet",
additional_authorized_imports=["numpy", "pandas"],
description="Summarize an sheet. Give it the path to the excel sheet as an argument to `task`",
)
excel_summarizer_agent.prompt_templates["system_prompt"] = (
"You are an expert excel file analyzer using. You read the file using pandas.read_excel(). You answer by giving descriptive statistics of excel file."
)
manager_agent = CodeAgent(
tools=[EnglishSpeechToTextTool(), ExecutePythonTool()],
# tools=[ExecutePythonTool()],
model=model,
managed_agents=[web_agent, excel_summarizer_agent, chess_analyzer_agent],
additional_authorized_imports=["time", "numpy", "pandas", "os"],
)
self.agent = manager_agent
print("BasicAgent initialized.")
def __call__(self, question: str, attachment) -> str:
print(f"Agent received question (first 50 chars): {question[:50]}...")
for k, v in cache.items():
if k in question and v is not None:
return v
images = []
if attachment:
for k, v in attachment.items():
if v.endswith(".png") or v.endswith(".jpg"):
image_content = Image.open(v).convert("RGB")
images = [image_content]
attachment = None
answer = self.agent.run(
question
+ " Please break down the questions into easier sub-tasks."
+ " Please answer concisely.",
additional_args=attachment,
images=images,
)
print("the answer", answer)
try:
return str(answer)
except Exception as e:
return json.dumps(answer)