File size: 7,647 Bytes
ab36e53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"""Custom tools go in here"""

from google import genai
from se_agents.tools import Tool
from se_agents.agent import Agent
from se_agents.runner import Runner
from openai import OpenAI
import types
import requests
from config import Config
from langchain_community.document_loaders import (
    UnstructuredExcelLoader,
    TextLoader,
    PyPDFLoader,
)
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
from openai import Client
from pathlib import Path
from utils import read_file_content
from google.genai import types


class YoutubeVideoInterpreter(Tool):
    def __init__(self):
        super().__init__(
            name="youtube_video_interpreter",
            description="Given a certain youtube video url, it analyzes the video and response any question asked by the user",
            parameters={
                "query": {
                    "type": "string",
                    "description": "question about the video",
                    "required": True,
                },
                "video_url": {
                    "type": "string",
                    "description": "the url of the video",
                    "required": True,
                },
            },
        )

    def execute(self, **kwargs) -> str:
        params = self._process_parameters(**kwargs)
        query = params.get("query")
        video_url = params.get("video_url")
        client = genai.Client(api_key=Config.get_gemini_api_key())
        response = client.models.generate_content(
            model="models/gemini-2.0-flash",
            contents=types.Content(
                parts=[
                    types.Part(file_data=types.FileData(file_uri=video_url)),
                    types.Part(text=query),
                ]
            ),
        )
        return response.text


class TaskFileDownloader(Tool):
    def __init__(self):
        super().__init__(
            name="task_file_downloader",
            description="Given a certain Taks id, it downloads the complementary file, outputs the path of the file",
            parameters={
                "task_id": {
                    "type": "string",
                    "description": "the id of the task",
                    "required": True,
                },
                "complementary_file": {
                    "type": "string",
                    "description": "the name with extension of the file",
                    "required": True,
                },
            },
        )

    def execute(self, **kwargs) -> str:
        params = self._process_parameters(**kwargs)
        task_id = params.get("task_id")
        complementary_file_ext = params.get("complementary_file").split(".")[-1]
        response = requests.get(f"{Config.get_default_api_url()}/files/{task_id}")
        # Verify the request was successful
        if response.status_code == 200:
            # Save the file
            with open(
                f"{Config.get_task_file_folder()}/{task_id}_complementary_file.{complementary_file_ext}",
                "wb",
            ) as file:
                file.write(response.content)
            return f"{Config.get_task_file_folder()}/{task_id}_complementary_file.{complementary_file_ext}"
        else:
            return f"Failed to retrieve file. Status code: {response.status_code}"


class RetriveInfoTaskFile(Tool):

    def __init__(self):
        super().__init__(
            name="retrive_info_task_file",
            description="Given a certain Taks file path, outputs info related to the file",
            parameters={
                "complementary_file": {
                    "type": "string",
                    "description": "the path with extension of the file",
                    "required": True,
                },
                "query": {
                    "type": "string",
                    "description": "question about the file",
                    "required": True,
                },
            },
        )
        self.retriver = {
            ".xlsx": UnstructuredExcelLoader,
            ".pdf": PyPDFLoader,
            ".txt": TextLoader,
        }

    def execute(self, **kwargs) -> str:
        params = self._process_parameters(**kwargs)
        complementary_file = params.get("complementary_file")
        query = params.get("query")
        complementary_file_path = Path(complementary_file)

        # Validate file format
        if complementary_file_path.suffix not in self.retriver:
            return f"Unsupported file format: {complementary_file_path.suffix}"

        # Load and process the document
        loader = self.retriver[complementary_file_path.suffix](complementary_file_path)
        documents = loader.load()
        text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=1000, chunk_overlap=100
        )
        docs = text_splitter.split_documents(documents)

        # Embed and retrieve relevant information
        embeddings = OpenAIEmbeddings()
        vectorstore = Chroma.from_documents(docs, embeddings)
        retriever = vectorstore.as_retriever()
        results = retriever.invoke(query)

        # Return formatted results or a fallback message
        return (
            "\n\n".join([doc.page_content for doc in results[:3]])
            if results
            else "No relevant information found."
        )


class SpeechToText(Tool):
    def __init__(self):
        super().__init__(
            name="speech_to_text",
            description="Given a certain audio file path, outputs the path to a .txt file with the transcription",
            parameters={
                "audio_file_path": {
                    "type": "string",
                    "description": "the name with extension of the file",
                    "required": True,
                },
            },
        )

    async def execute(self, **kwargs) -> str:
        params = self._process_parameters(**kwargs)
        audio_file_path = params.get("audio_file_path")
        client = OpenAI(api_key=Config.get_openai_api_key())
        if Path(audio_file_path).exists():
            with open(audio_file_path, "rb") as audio_file:
                transcription = client.audio.transcriptions.create(
                    model="gpt-4o-transcribe", file=audio_file
                )

                # Write transcription to a .txt file
                txt_file_path = Path(audio_file_path).with_suffix(".txt")
                with open(txt_file_path, "w") as txt_file:
                    txt_file.write(transcription.text)

                return f"Transcription saved to {txt_file_path}"
        else:
            return "Audio file does not exist"


class CodeInterpreter(Tool):
    def __init__(self):
        super().__init__(
            name="code_interpreter",
            description="Given a certain code file path, outputs the content of the file",
            parameters={
                "code_file_path": {
                    "type": "string",
                    "description": "the name with extension of the file",
                    "required": True,
                },
            },
        )

    async def execute(self, **kwargs) -> str:
        params = self._process_parameters(**kwargs)
        code_file_path = params.get("code_file_path")
        client = OpenAI(api_key=Config.get_openai_api_key())
        if Path(code_file_path).exists():
            content = read_file_content(code_file_path)
            return content
        else:
            return "Code file does not exist"