File size: 10,980 Bytes
2144dc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import io
import os
import re
import sys
from typing import List, Callable, Any

import openai
import pandas as pd
import requests
from dotenv import load_dotenv
from google import genai
from google.genai import types
from langchain_community.document_loaders import WebBaseLoader, ImageCaptionLoader, WikipediaLoader, ArxivLoader
from langchain_community.tools import DuckDuckGoSearchResults
from langchain_core.tools import tool
from langchain_text_splitters import CharacterTextSplitter

DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"

load_dotenv()


@tool(description="Multiply two integers and return the result")
def multiply(a: int, b: int) -> int:
    return a * b


@tool(description="Add two integers and return the result")
def add(a: int, b: int) -> int:
    return a + b


@tool(description="Subtract the second integer from the first and return the result")
def subtract(a: int, b: int) -> int:
    return a - b


@tool(
    description="Divide the first integer by the second and return the result; raises an error if the second integer is zero")
def divide(a: int, b: int) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero.")
    return a / b


@tool(description="Return the remainder of dividing the first integer by the second")
def modulus(a: int, b: int) -> int:
    return a % b


@tool(description="""
    Searches for a Wikipedia articles using the provided query and returns the content of the corresponding Wikipedia pages.
    Args:
        query (str): The search term to look up on Wikipedia.
    Returns:
        str: The text content of the Wikipedia articles related to the query.
    """)
def wiki_search(query: str) -> str:
    print("wiki_search called with:", query)
    search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
    formatted_search_docs = "\n\n---\n\n".join(
        [
            f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
            for doc in search_docs
        ])
    return formatted_search_docs


@tool(description="""
    Fetches raw HTML content of a web page.
    Args:
        url: the webpage url
    Returns:
        str: The combined raw text content of the webpage
    """)
def visit_webpage(url: str) -> str:
    try:
        response = requests.get(url, timeout=5)
        return response.text[:5000]
    except Exception as e:
        return f"[ERROR fetching {url}]: {str(e)}"


@tool(description="""
    Performs a web search using the given query, downloads the content of two relevant web pages,
    and returns their combined content as a raw string.
    This is useful when the task requires analysis of web page content, such as retrieving poems, 
    changelogs, or other textual resources.
    Args:
        query (str): The search query.
    Returns:
        str: The combined raw text content of the two retrieved web pages.
    """)
def duckduck_websearch(query: str) -> str:
    search_engine = DuckDuckGoSearchResults(output_format="list", num_results=2)
    results = search_engine.invoke({"query": query})
    page_urls = [url["link"] for url in results]

    loader = WebBaseLoader(web_paths=page_urls)
    docs = loader.load()

    combined_text = "\n\n".join(doc.page_content[:15000] for doc in docs)

    # Clean up excessive newlines, spaces and strip leading/trailing whitespace
    cleaned_text = re.sub(r'\n{3,}', '\n\n', combined_text).strip()
    cleaned_text = re.sub(r'[ \t]{6,}', ' ', cleaned_text)

    # Strip leading/trailing whitespace
    cleaned_text = cleaned_text.strip()
    return cleaned_text


@tool(description="""
    Splits text into chunks using LangChain's CharacterTextSplitter.
    Args:
        text: A string of text to split.
    Returns:
        List[str]: a list of split text
    """)
def text_splitter(text: str) -> List[str]:
    splitter = CharacterTextSplitter(chunk_size=450, chunk_overlap=10)
    return splitter.split_text(text)


@tool(description="""
    First download the file, then read its content
    Args:
        dir: the task_id
    Returns:
        str: the file content
    """)
def read_file(task_id: str) -> str:
    file_url = f'{DEFAULT_API_URL}/files/{task_id}'
    r = requests.get(file_url, timeout=15, allow_redirects=True)
    with open('temp', "wb") as fp:
        fp.write(r.content)
    with open('temp') as f:
        return f.read()


@tool(description="""
    First download the excel file, then read its content
    Args:
        task_id: the task_id
    Returns:
        str: the content of excel file
    """)
def excel_read(task_id: str) -> str:
    try:
        file_url = f'{DEFAULT_API_URL}/files/{task_id}'
        r = requests.get(file_url, timeout=15, allow_redirects=True)
        with open('temp.xlsx', "wb") as fp:
            fp.write(r.content)
        # Read the Excel file
        df = pd.read_excel('temp.xlsx')
        # Run various analyses based on the query
        result = (
            f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
        )
        result += f"Columns: {', '.join(df.columns)}\n\n"
        # Add summary statistics
        result += "Summary statistics:\n"
        result += str(df.describe())
        return result
    except Exception as e:
        return f"Error analyzing Excel file: {str(e)}"


@tool(description="""
    First download the csv file, then read its content
    Args:
        dir: the task_id
    Returns:
        str: the content of csv file
    """)
def csv_read(task_id: str) -> str:
    try:
        file_url = f'{DEFAULT_API_URL}/files/{task_id}'
        r = requests.get(file_url, timeout=15, allow_redirects=True)
        with open('temp.csv', "wb") as fp:
            fp.write(r.content)
        # Read the CSV file
        df = pd.read_csv('temp.csv')
        # Run various analyses based on the query
        result = (
            f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
        )
        result += f"Columns: {', '.join(df.columns)}\n\n"
        # Add summary statistics
        result += "Summary statistics:\n"
        result += str(df.describe())
        return result
    except Exception as e:
        return f"Error analyzing CSV file: {str(e)}"


@tool(description="""
    Understand the content of the provided image
    Args:
        dir: the image url link
    Returns:
        str: the image caption
    """)
def image_caption(task_id: str) -> str:
    file_url = f'{DEFAULT_API_URL}/files/{task_id}'
    loader = ImageCaptionLoader(images=[file_url])
    metadata = loader.load()
    return metadata[0].page_content


@tool(description="""
    Analyzes a YouTube video from the provided URL and returns an answer 
    to the given question based on the analysis results.
    Args:
        youtube_url (str): The URL of the YouTube video, in the format 
            "https://www.youtube.com/...".
        question (str): A question related to the content of the video.
    Returns:
        str: An answer to the question based on the video's content.
    """)
def youtube_search(youtube_url: str, question: str) -> str:
    client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
    response = client.models.generate_content(
        model='models/gemini-2.5-flash',
        contents=types.Content(
            parts=[
                types.Part(
                    file_data=types.FileData(file_uri=youtube_url)
                ),
                types.Part(text=question)
            ]
        )
    )
    return response.text


@tool(description=
      """Search Arxiv for a query and return maximum 3 result.
    Args:
        query: The search query.""")
def arvix_search(query: str) -> str:
    search_docs = ArxivLoader(query=query, load_max_docs=3).load()
    formatted_search_docs = "\n\n---\n\n".join(
        [
            f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
            for doc in search_docs
        ])
    return formatted_search_docs


@tool(description= """
    First download the mp3 file, then listen to it
    
    Args:
        dir: the task_id
    
    Returns:
        str: the content of mp3 file
    """)
def whisper_transcribe_api(task_id: str) -> str:
    openai.api_key = os.getenv("OPENAI_API_KEY")
    file_url = f'{DEFAULT_API_URL}/files/{task_id}'

    try:
        r = requests.get(file_url, timeout=15, allow_redirects=True)
        temp_path = 'temp.mp3'
        with open(temp_path, "wb") as fp:
            fp.write(r.content)
        with open(temp_path, "rb") as audio_file:
            transcript = openai.audio.transcriptions.create(
                file=audio_file,
                model="whisper-1"
            )
        return transcript.text
    except Exception as e:
        return f"Error transcribing audio: {e}"


@tool(description="""
Execute Python code from a file identified by task_id and file_name.
Returns the numeric result if defined, otherwise stdout.
""")
def run_python_file(task_id: str, file_name: str) -> str:
    file_path = file_name
    buffer = io.StringIO()
    old_stdout = sys.stdout
    ns = {"__builtins__": __builtins__, "__name__": "__main__"}
    try:
        file_url = f"{DEFAULT_API_URL}/files/{task_id}"
        r = requests.get(file_url, timeout=15, allow_redirects=True)
        if r.status_code != 200:
            return f"❌ Failed to download file: {r.status_code}"

        with open(file_path, "wb") as f:
            f.write(r.content)

        with open(file_path, "r", encoding="utf-8", errors="replace") as f:
            code = f.read()

        sys.stdout = buffer
        try:
            compiled = compile(code, file_path, "exec")
            exec(compiled, ns, ns)
        finally:
            sys.stdout = old_stdout

        if "result" in ns:
            return str(ns["result"])
        else:
            output = buffer.getvalue().strip()
            return output or "No output produced."

    except Exception as e:
        # Prefer returning a computed result or any partial stdout if available
        try:
            sys.stdout = old_stdout
        except Exception:
            pass
        if "result" in ns:
            return str(ns["result"])
        output = buffer.getvalue().strip()
        if output:
            return output
        return f"❌ Error executing Python file: {e}"
    finally:
        # Ensure the downloaded code file is removed after execution
        try:
            if os.path.exists(file_path):
                os.remove(file_path)
        except Exception:
            pass



TOOLS: List[Callable[..., Any]] = [
    multiply,
    add,
    subtract,
    divide,
    modulus,
    duckduck_websearch,
    arvix_search,
    wiki_search,
    visit_webpage,
    youtube_search,
    text_splitter,
    read_file,
    excel_read,
    csv_read,
    image_caption,
    whisper_transcribe_api,
    run_python_file
]