File size: 9,919 Bytes
12c47a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61be22b
 
12c47a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
887480a
 
 
 
 
 
 
 
 
 
8eea4d3
 
 
 
 
12c47a4
 
 
 
 
3064810
12c47a4
 
 
 
 
 
 
 
887480a
 
8eea4d3
12c47a4
 
 
 
 
 
 
6692c96
12c47a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36a7313
12c47a4
36a7313
12c47a4
 
 
 
 
 
 
 
 
 
 
 
 
887480a
12c47a4
 
 
 
 
6692c96
12c47a4
 
 
 
 
 
 
8eea4d3
12c47a4
 
 
 
 
 
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
import os
from dotenv import load_dotenv

load_dotenv()


from llama_index.core.agent import ReActAgent
from llama_index.core.tools import FunctionTool
from llama_index.llms.openrouter import OpenRouter

import tools


class LlamaIndexAgent:
    def __init__(
        self,
        # model_name: str = "meta-llama/llama-4-maverick:free",
        # model_name: str = "meta-llama/llama-4-scout:free",
        # model_name: str = "microsoft/phi-4-reasoning-plus:free",
        model_name: str = "google/gemini-2.5-flash-preview",
        # model_name: str = "x-ai/grok-3-beta",
        temperature: float = 0.7,
        verbose: bool = True,
    ):
        """
        Initialize the LlamaIndex agent with OpenRouter LLM.

        Args:
            openrouter_api_key: API key for OpenRouter
            model_name: Model name to use from OpenRouter
            temperature: Temperature setting for the LLM
            verbose: Whether to output verbose logs
        """
        self.llm = OpenRouter(
            api_key=os.getenv("OPENROUTER_API_KEY"),
            model=model_name,
            temperature=temperature,
        )

        # Define tools
        reverse_tool = FunctionTool.from_defaults(
            fn=tools.reverse_text,
            name="reverse_text",
            description="Reverses the given text",
        )

        final_answer_tool = FunctionTool.from_defaults(
            fn=tools.final_answer,
            name="final_answer",
            description="Use this to provide your final answer to the user's question",
        )
        web_search_tool = FunctionTool.from_defaults(
            fn=tools.web_search,
            name="web_search",
            description="Use this to search the web for the given query",
        )
        wikipedia_search_tool = FunctionTool.from_defaults(
            fn=tools.wikipedia_search,
            name="wikipedia_search",
            description="Use this to search the wikipedia for the given query",
        )
        multiply_tool = FunctionTool.from_defaults(
            fn=tools.multiply,
            name="multiply",
            description="Use this to multiply two numbers",
        )
        length_tool = FunctionTool.from_defaults(
            fn=tools.length,
            name="length",
            description="Use this to get the length of an iterable",
        )
        execute_python_file_tool = FunctionTool.from_defaults(
            fn=tools.execute_python_file,
            name="execute_python_file",
            description="Use this to execute a python file",
        )
        transcript_youtube_tool = FunctionTool.from_defaults(
            fn=tools.trascript_youtube,
            name="transcript_youtube",
            description="Use this to get the transcript of a YouTube video",
        )
        classify_fruit_vegitable_tool = FunctionTool.from_defaults(
            fn=tools.classify_fruit_vegitable,
            name="classify_fruit_vegitable",
            description="Use this to classify items to fruits and vegitables",
        )
        fetch_historical_event_data_tool = FunctionTool.from_defaults(
            fn=tools.fetch_historical_event_data,
            name="fetch_historical_event_data",
            description="Use this to fetch data about historical event that occured in certain year such as Olympics games, Footbal games, NBA etc.",
        )
        read_excel_tool = FunctionTool.from_defaults(
            fn=tools.read_excel,
            name="read_excel",
            description="Use this to read excel file",
        )
        pandas_column_sum_tool = FunctionTool.from_defaults(
            fn=tools.pandas_column_sum,
            name="pandas_column_sum",
            description="Use this to compute sum on pandas dataframe column",
        )
        compute_sum_tool = FunctionTool.from_defaults(
            fn=tools.compute_sum,
            name="compute_sum",
            description="Use this to compute sum of provided values",
        )

        # Create the agent
        self.agent = ReActAgent.from_tools(
            [
                reverse_tool,
                # final_answer_tool,
                web_search_tool,
                wikipedia_search_tool,
                multiply_tool,
                length_tool,
                execute_python_file_tool,
                transcript_youtube_tool,
                classify_fruit_vegitable_tool,
                fetch_historical_event_data_tool,
                read_excel_tool,
                pandas_column_sum_tool,
                compute_sum_tool,
            ],
            llm=self.llm,
            verbose=verbose,
            max_iterations=20,
            system_prompt="""
            You are a helpful AI assistant that can use tools to answer the user's questions.
            You have set of tools that you are free to use.
            You can do web search, parse wikipedia, execute python scripts, read xlsx, get youtube video transcript from youtube link, reverse texts, fetch historical events.
            When you have the complete answer to the user's question, always use the final_answer tool to present it.
            """,
        )

    def __call__(self, query_text: str, **kwds) -> str:
        """
        Process a user query through the agent.

        Args:
            query_text: User's query text

        Returns:
            The agent's response
        """
        try:
            response = self.agent.chat(query_text).response
        except:
            response = ""
        final_response = tools.final_answer(answer=response)

        return final_response


if __name__ == "__main__":
    agent = LlamaIndexAgent()

    # Queries
    example_queries = [
        # '.rewsna eht sa "tfel" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI',
        # "What is the weather in Lviv now?",
        # "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.",
        # "Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide 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.",
        # "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?"
        # "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.",
        # "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."
        # "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
        # "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?",
        # "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.",
        # "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?",
        # "What is the final numeric output from the attached Python code? File name: f918266a-b3e0-4914-865d-4faa564f1aef.py",
        # """Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\"""",
        # "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?",
        # """
        # 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:\n\nmilk, 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\n\nI 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.
        # """,
        # """
        # 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?
        # """,
        # "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.\nAttached file: 7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx",
    ]

    for query in example_queries:
        print(f"\nQuery: {query}")
        response = agent(query)
        print(f"Response: {response}")