File size: 9,285 Bytes
1af9028
 
 
 
 
 
 
 
 
 
413ad0f
1af9028
 
 
 
 
fd14ef2
 
 
 
 
 
 
 
 
 
 
 
1af9028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afadec7
1af9028
 
 
 
 
 
d5411e4
1af9028
d5411e4
1af9028
fd14ef2
 
 
 
 
 
 
 
 
 
 
 
1af9028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5411e4
1af9028
 
 
 
 
 
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


import os
import yaml
from dotenv import load_dotenv

from pathlib import Path

from smolagents import CodeAgent, GradioUI, OpenAIServerModel

from smolagents.default_tools import (DuckDuckGoSearchTool, 
                                      VisitWebpageTool, 
                                      WikipediaSearchTool, 
                                      SpeechToTextTool,
                                      PythonInterpreterTool)
#from final_answer import FinalAnswerTool, check_reasoning, ensure_formatting
from tools_smolagent import (multiply,
    add,
    subtract,
    divide,
    modulus,
    read_file, 
    extract_text_from_image, 
    analyze_csv_file, 
    analyze_excel_file, 
    youtube_transcribe, 
    transcribe_audio, 
    wikipedia_search)

load_dotenv()

def get_system_prompt(prompt_file: Path = None):
    """
    Loads a system prompt from a YAML file.

    Args:
        prompt_file: Path to the YAML file (defaults to 'system_prompt.yaml').

    Returns:
        A dictionary containing the parsed YAML content.
    """
    if prompt_file is None:
        prompt_file = Path("system_prompt.yaml")
    
    with prompt_file.open("r", encoding="utf-8") as f:
        system_prompt = yaml.safe_load(f)  # Devuelve un dict

    return system_prompt
    
def build_agent():
    model_desp = OpenAIServerModel(
        model_id="gpt-4o",
        api_base="https://api.openai.com/v1",
        api_key=os.environ["OPENAI_API_KEY"],
)
    return CodeAgent(
        model=model_desp,
        tools=[#FinalAnswerTool(), 
            DuckDuckGoSearchTool(), 
            VisitWebpageTool(max_output_length=500000), 
            #WikipediaSearchTool(extract_format='HTML'),
            SpeechToTextTool(),
            multiply,
            add,
            subtract,
            divide,
            modulus,
            read_file, 
            extract_text_from_image, 
            analyze_csv_file, 
            analyze_excel_file, 
            youtube_transcribe, 
            transcribe_audio, 
            wikipedia_search
            ],
        managed_agents=[],
        additional_authorized_imports=['os', 'pandas', 'numpy', 'PIL', 'tempfile', 'PIL.Image'],
        max_steps=10,
        verbosity_level=1,
        planning_interval=10,
        name="Manager",
        description="The manager of the team, responsible for overseeing and guiding the team's work.",
    )

class MyGAIAAgent:
    def __init__(self, verbose: bool = False):
        print("MyAgent initialized.")
        self.agent = build_agent()
        self.verbose = verbose
    def __call__(self, task: dict) -> str:
        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)]}
        answer = self.agent.run(user_prompt)
        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



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?"
    task = {
        "task_id": "8e867cd7-cff9-4e6c-867a-ff5ddc2550be",
        "question": question1,
        "Level": "1",
        "file_name": "",
    }
    
    agent = MyGAIAAgent()
    print(agent(task))