h2oaimichalmarszalek commited on
Commit
3469f37
·
1 Parent(s): 81917a3

development

Browse files
Files changed (10) hide show
  1. .gitignore +1 -0
  2. Makefile +9 -0
  3. agent.py +49 -0
  4. app.py +3 -10
  5. local_development.py +42 -0
  6. questions.json +122 -0
  7. requirements.txt +13 -1
  8. tools/audio.py +60 -0
  9. tools/utils.py +232 -0
  10. tools/youtube.py +42 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__
Makefile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ .PHONY: clean
3
+ clean:
4
+ rm -rf ./downloaded_files || true
5
+
6
+ .PHONY: install
7
+ install:
8
+ pip install -r ./requirements.txt
9
+
agent.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from pathlib import Path
4
+ from typing import Optional
5
+ from smolagents import CodeAgent, PythonInterpreterTool, DuckDuckGoSearchTool, Tool
6
+ from tools.utils import reverse_string, process_excel_file, is_text_file, execute_python_file, get_ingredients
7
+ from tools.youtube import load_youtube
8
+ from tools.audio import transcribe_audio
9
+
10
+ # from langchain.agents import load_tools
11
+
12
+ # model = LiteLLMModel(
13
+ # model_id="ollama/qwen2.5:7b",
14
+ # api_base="http://localhost:11434"
15
+ # )
16
+
17
+ class BasicAgent:
18
+ def __init__(self, model):
19
+ self._model = model
20
+ self._agent = CodeAgent(
21
+ tools=[PythonInterpreterTool(), DuckDuckGoSearchTool(), reverse_string, process_excel_file, is_text_file, load_youtube, execute_python_file, transcribe_audio, get_ingredients],
22
+ additional_authorized_imports=['random', 'time', 'itertools', 'pandas'],
23
+ model=model
24
+ )
25
+ print("BasicAgent initialized.")
26
+
27
+ def __call__(self, question: str, file_path: Optional[str] = None) -> str:
28
+ # print(f"Agent received question (first 50 chars): {question[:50]}...")
29
+ if file_path and os.path.exists(file_path):
30
+ try:
31
+ file = Path(file_path)
32
+ if is_text_file(file_path):
33
+ with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
34
+ file_content = f.read()
35
+ if file.suffix == '.py':
36
+ question += f"\nAttached Python code:\n{file_path}"
37
+ else:
38
+ question += f"\nAttached File Content:\n{file_content}"
39
+ else:
40
+ if file.suffix == '.mp3':
41
+ question += f"\nUse tool transcribe_audio to extract text from mp3 file.\nAttached mp3 file to transcribes:\n{file_path}"
42
+ else:
43
+ question += f"\nAttached File Path:\n{file_path}"
44
+ except Exception as e:
45
+ print(f"Failed to read file: {e}")
46
+ print(question)
47
+ answer = self._agent.run(question)
48
+ print(f"Agent returning answer: {answer}")
49
+ return answer
app.py CHANGED
@@ -4,20 +4,13 @@ import requests
4
  import inspect
5
  import pandas as pd
6
 
 
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
14
- def __init__(self):
15
- print("BasicAgent initialized.")
16
- def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
 
4
  import inspect
5
  import pandas as pd
6
 
7
+ from agent import BasicAgent
8
+
9
  # (Keep Constants as is)
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
13
+
 
 
 
 
 
 
 
 
 
14
 
15
  def run_and_submit_all( profile: gr.OAuthProfile | None):
16
  """
local_development.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import random
4
+ from agent import BasicAgent
5
+ from smolagents import LiteLLMModel
6
+ from tools.utils import download_file
7
+
8
+
9
+ if __name__ == '__main__':
10
+ parser = argparse.ArgumentParser()
11
+ parser.add_argument("--id", required=False, type=str, help="Number of question to load", default=None)
12
+ args = parser.parse_args()
13
+ questions = []
14
+ question = None
15
+ file_path = None
16
+ base_url = 'https://agents-course-unit4-scoring.hf.space'
17
+
18
+ with open('questions.json', 'r') as s:
19
+ questions = json.load(s)
20
+ if args.id:
21
+ question = [q for q in questions if q['task_id'] == args.id][0]
22
+ print(f"Process question: {question.get('question')[:50]}")
23
+ else:
24
+ n = random.randint(0, len(questions))
25
+ question = questions[n]
26
+ print(f"Process random question: {question.get('question')[:50]}")
27
+
28
+ file_name = question.get('file_name')
29
+ prompt = question.get('question')
30
+
31
+ if file_name:
32
+ task_id = question.get('task_id')
33
+ file_path = download_file(f'{base_url}/files/{task_id}', file_name)
34
+
35
+
36
+ model = LiteLLMModel(
37
+ model_id="ollama/qwen2.5:7b",
38
+ api_base="http://localhost:11434"
39
+ )
40
+ agent = BasicAgent(model)
41
+ response = agent(prompt, file_path)
42
+ print(response)
questions.json ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "task_id": "8e867cd7-cff9-4e6c-867a-ff5ddc2550be",
4
+ "question": "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.",
5
+ "Level": "1",
6
+ "file_name": ""
7
+ },
8
+ {
9
+ "task_id": "a1e91b78-d3d8-4675-bb8d-62741b4b68a6",
10
+ "question": "In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?",
11
+ "Level": "1",
12
+ "file_name": ""
13
+ },
14
+ {
15
+ "task_id": "2d83110e-a098-4ebb-9987-066c06fa42d0",
16
+ "question": ".rewsna eht sa \"tfel\" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI",
17
+ "Level": "1",
18
+ "file_name": ""
19
+ },
20
+ {
21
+ "task_id": "cca530fc-4052-43b2-b130-b30968d8aa44",
22
+ "question": "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.",
23
+ "Level": "1",
24
+ "file_name": "cca530fc-4052-43b2-b130-b30968d8aa44.png"
25
+ },
26
+ {
27
+ "task_id": "4fc2f1ae-8625-45b5-ab34-ad4433bc21f8",
28
+ "question": "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?",
29
+ "Level": "1",
30
+ "file_name": ""
31
+ },
32
+ {
33
+ "task_id": "6f37996b-2ac7-44b0-8e68-6d28256631b4",
34
+ "question": "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.",
35
+ "Level": "1",
36
+ "file_name": ""
37
+ },
38
+ {
39
+ "task_id": "9d191bce-651d-4746-be2d-7ef8ecadb9c2",
40
+ "question": "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?\"",
41
+ "Level": "1",
42
+ "file_name": ""
43
+ },
44
+ {
45
+ "task_id": "cabe07ed-9eca-40ea-8ead-410ef5e83f91",
46
+ "question": "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?",
47
+ "Level": "1",
48
+ "file_name": ""
49
+ },
50
+ {
51
+ "task_id": "3cef3a44-215e-4aed-8e3b-b1e3f08063b7",
52
+ "question": "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.",
53
+ "Level": "1",
54
+ "file_name": ""
55
+ },
56
+ {
57
+ "task_id": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3",
58
+ "question": "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. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can't quite make out what she's saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I've attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for \"a pinch of salt\" or \"two cups of ripe strawberries\" the ingredients on the list would be \"salt\" and \"ripe strawberries\".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.",
59
+ "Level": "1",
60
+ "file_name": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3"
61
+ },
62
+ {
63
+ "task_id": "305ac316-eef6-4446-960a-92d80d542f82",
64
+ "question": "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.",
65
+ "Level": "1",
66
+ "file_name": ""
67
+ },
68
+ {
69
+ "task_id": "f918266a-b3e0-4914-865d-4faa564f1aef",
70
+ "question": "What is the final numeric output from the attached Python code?",
71
+ "Level": "1",
72
+ "file_name": "f918266a-b3e0-4914-865d-4faa564f1aef.py"
73
+ },
74
+ {
75
+ "task_id": "3f57289b-8c60-48be-bd80-01f8099ca449",
76
+ "question": "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?",
77
+ "Level": "1",
78
+ "file_name": ""
79
+ },
80
+ {
81
+ "task_id": "1f975693-876d-457b-a649-393859e79bf3",
82
+ "question": "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 :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",
83
+ "Level": "1",
84
+ "file_name": "1f975693-876d-457b-a649-393859e79bf3.mp3"
85
+ },
86
+ {
87
+ "task_id": "840bfca7-4f7b-481a-8794-c560c340185d",
88
+ "question": "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?",
89
+ "Level": "1",
90
+ "file_name": ""
91
+ },
92
+ {
93
+ "task_id": "bda648d7-d618-4883-88f4-3466eabd860e",
94
+ "question": "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.",
95
+ "Level": "1",
96
+ "file_name": ""
97
+ },
98
+ {
99
+ "task_id": "cf106601-ab4f-4af9-b045-5295fe67b37d",
100
+ "question": "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.",
101
+ "Level": "1",
102
+ "file_name": ""
103
+ },
104
+ {
105
+ "task_id": "a0c07678-e491-4bbc-8f0b-07405144218f",
106
+ "question": "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.",
107
+ "Level": "1",
108
+ "file_name": ""
109
+ },
110
+ {
111
+ "task_id": "7bd855d8-463d-4ed5-93ca-5fe35145f733",
112
+ "question": "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.",
113
+ "Level": "1",
114
+ "file_name": "7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx"
115
+ },
116
+ {
117
+ "task_id": "5a0c1adf-205e-4841-a666-7c3ef95def9d",
118
+ "question": "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?",
119
+ "Level": "1",
120
+ "file_name": ""
121
+ }
122
+ ]
requirements.txt CHANGED
@@ -1,2 +1,14 @@
1
  gradio
2
- requests
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  gradio
2
+ requests
3
+ smolagents
4
+ smolagents[litellm]
5
+ duckduckgo-search
6
+ pandas
7
+ openpyxl
8
+ youtube_transcript_api
9
+ pytube
10
+ langchain
11
+ langchain-community
12
+ backoff
13
+ SpeechRecognition
14
+ pydub
tools/audio.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import speech_recognition as sr
2
+ import os
3
+ from pydub import AudioSegment
4
+ from smolagents import tool
5
+
6
+
7
+ @tool
8
+ def transcribe_audio(mp3_path: str) -> str:
9
+ """
10
+ Transcribes text from an MP3 audio file using speech recognition.
11
+
12
+ Args:
13
+ mp3_path (str): Path to the MP3 file to be transcribed.
14
+
15
+ Returns:
16
+ str: The transcribed text from the audio file.
17
+
18
+ Raises:
19
+ FileNotFoundError: If the MP3 file does not exist at the specified path.
20
+ ValueError: If the file is not a valid MP3 file or audio cannot be processed.
21
+ Exception: For other unexpected errors during transcription.
22
+
23
+ Example:
24
+ >>> text = transcribe_audio("sample.mp3")
25
+ >>> print(text)
26
+ "Hello, this is a sample audio."
27
+ """
28
+ # Check if file exists
29
+ if not os.path.exists(mp3_path):
30
+ raise FileNotFoundError(f"The file {mp3_path} does not exist.")
31
+
32
+ # Initialize recognizer
33
+ recognizer = sr.Recognizer()
34
+
35
+ try:
36
+ # Convert MP3 to WAV
37
+ audio = AudioSegment.from_mp3(mp3_path)
38
+ wav_path = mp3_path.replace(".mp3", ".wav")
39
+ audio.export(wav_path, format="wav")
40
+
41
+ # Load audio file
42
+ with sr.AudioFile(wav_path) as source:
43
+ # Adjust for ambient noise
44
+ recognizer.adjust_for_ambient_noise(source)
45
+ # Record the audio
46
+ audio_data = recognizer.record(source)
47
+
48
+ # Clean up temporary WAV file
49
+ os.remove(wav_path)
50
+
51
+ # Perform speech recognition
52
+ text = recognizer.recognize_google(audio_data)
53
+ return text
54
+
55
+ except sr.UnknownValueError:
56
+ raise ValueError("Could not understand the audio.")
57
+ except sr.RequestError as e:
58
+ raise ValueError(f"Could not process audio; {e}")
59
+ except Exception as e:
60
+ raise Exception(f"An error occurred during transcription: {e}")
tools/utils.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Union
3
+ import requests
4
+ import pandas as pd
5
+ import subprocess
6
+ import sys
7
+ from smolagents import tool
8
+
9
+
10
+ @tool
11
+ def reverse_string(text: str) -> str:
12
+ """
13
+ Reverse the order of characters in a given string.
14
+
15
+ Args:
16
+ text (str): The input string to be reversed.
17
+
18
+ Returns:
19
+ str: A new string with characters in reverse order.
20
+
21
+ Example:
22
+ >>> reverse_string("hello")
23
+ 'olleh'
24
+ >>> reverse_string("Python")
25
+ 'nohtyP'
26
+ """
27
+ return text[::-1]
28
+
29
+
30
+ def download_file(url: str, filename: str) -> str:
31
+ """
32
+ Download a file from the given URL and save it to a temporary location.
33
+
34
+ Args:
35
+ url (str): The URL of the file to download.
36
+ filename (str): The name to use for the saved file.
37
+
38
+ Returns:
39
+ str: Full path to the downloaded file in temporary directory.
40
+
41
+ Raises:
42
+ requests.RequestException: If the download fails.
43
+
44
+ Example:
45
+ >>> path = download_file("https://example.com/data.json", "my_data.json")
46
+ >>> print(path)
47
+ '/tmp/tmpxyz123/my_data.json'
48
+ """
49
+
50
+ file_path = os.path.join("downloaded_files", filename)
51
+ if not os.path.exists(file_path):
52
+ print(f"Attempting to download file from: {url}")
53
+ try:
54
+ response = requests.get(url, timeout=30)
55
+ response.raise_for_status()
56
+ os.makedirs("downloaded_files", exist_ok=True)
57
+ with open(file_path, "wb") as f:
58
+ f.write(response.content)
59
+ except requests.exceptions.RequestException as e:
60
+ print(f"Error downloading file: {e}")
61
+ return file_path
62
+
63
+ @tool
64
+ def process_excel_file(file_path: str) -> pd.DataFrame:
65
+ """
66
+ Process an Excel file and return its data as Pandas DataFrame.
67
+ Args:
68
+ file_path (str): Path to the Excel file (.xlsx or .xls).
69
+
70
+ Returns:
71
+ pd.DataFrame: processed DataFrame.
72
+
73
+ Example:
74
+ >>> result = process_excel_file(
75
+ ... "data.xlsx",
76
+ ... )
77
+ >>> print(result.head())
78
+ """
79
+ return pd.read_excel(file_path)
80
+
81
+
82
+ @tool
83
+ def is_text_file(file_path: str) -> bool:
84
+ """Check if a file is a text file by attempting to decode it as UTF-8.
85
+
86
+ Args:
87
+ file_path (str): Path to the file to check.
88
+
89
+ Returns:
90
+ bool: True if the file is likely a text file, False if it is likely binary
91
+ or an error occurs.
92
+
93
+ Raises:
94
+ None: All exceptions are caught and handled internally.
95
+
96
+ Example:
97
+ >>> is_text_file("example.txt")
98
+ True
99
+ >>> is_text_file("image.png")
100
+ False
101
+ """
102
+ try:
103
+ with open(file_path, 'rb') as file:
104
+ # Read a small chunk of the file (1024 bytes)
105
+ chunk: bytes = file.read(1024)
106
+ # Try decoding as UTF-8 text
107
+ chunk.decode('utf-8')
108
+ return True # No decoding errors, likely a text file
109
+ except UnicodeDecodeError:
110
+ return False # Decoding failed, likely a binary file
111
+ except Exception as e:
112
+ print(f"Error reading file: {e}")
113
+ return False
114
+
115
+
116
+ @tool
117
+ def execute_python_file(file_path: str) -> Union[str|float]:
118
+ """
119
+ Execute a Python code from file_path in a separate process and return its output as a numeric value.
120
+
121
+ This function runs the specified Python file using the Python interpreter
122
+ in a separate subprocess with error handling and a 60-second timeout.
123
+
124
+ Args:
125
+ file_path (str): Path to the Python file to execute.
126
+
127
+ Returns:
128
+ Union[str|float]: The output from the executed script, or an error message if execution failed. If output is numeric return float in the other case returns str.
129
+
130
+ Raises:
131
+ None: All exceptions are handled internally and returned as error strings.
132
+
133
+ Examples:
134
+ >>> output = execute_python_file("script.py")
135
+ >>> print(output)
136
+ "Hello, World!"
137
+
138
+ >>> output = execute_python_file("nonexistent.py")
139
+ >>> print(output)
140
+ "Error: File not found: nonexistent.py"
141
+ """
142
+ # Check if file exists
143
+ if not os.path.exists(file_path):
144
+ return f"Error: File not found: {file_path}"
145
+
146
+ # Check if file is actually a Python file
147
+ if not file_path.endswith('.py'):
148
+ return f"Error: File is not a Python file: {file_path}"
149
+
150
+ try:
151
+ # Execute the Python file in a separate process
152
+ result = subprocess.run(
153
+ [sys.executable, file_path],
154
+ capture_output=True,
155
+ text=True,
156
+ timeout=60 # 60 seconds timeout
157
+ )
158
+
159
+ # If there's stderr output, include it in the result
160
+ if result.stderr and result.returncode != 0:
161
+ return f"Error: {result.stderr.strip()}"
162
+ elif result.stderr:
163
+ # Include stderr even if return code is 0 (warnings, etc.)
164
+ return f"{result.stdout.strip()}\nWarnings/Info: {result.stderr.strip()}"
165
+ else:
166
+ try:
167
+ return float(result.stdout.strip())
168
+ except:
169
+ return result.stdout.strip() if result.stdout.strip() else "Script executed successfully with no output"
170
+
171
+ except subprocess.TimeoutExpired:
172
+ return "Error: Execution timed out after 60 seconds"
173
+
174
+ except subprocess.SubprocessError as e:
175
+ return f"Error: Subprocess error: {str(e)}"
176
+
177
+ except Exception as e:
178
+ return f"Error: Unexpected error: {str(e)}"
179
+
180
+ @tool
181
+ def get_ingredients(item: str) -> str:
182
+ """
183
+ Extract known ingredients from a given text string.
184
+
185
+ This function identifies and extracts recognized ingredients (fruits, vegetables,
186
+ and common cooking products) from the input text and returns them as a
187
+ comma-separated string.
188
+
189
+ Args:
190
+ item (str): Input text containing potential ingredient names separated by spaces.
191
+
192
+ Returns:
193
+ str: Comma-separated string of recognized ingredients in alphabetical order.
194
+ Returns empty string if no recognized ingredients are found.
195
+
196
+ Examples:
197
+ >>> get_ingredients("apple banana flour")
198
+ "apple,banana,flour"
199
+
200
+ >>> get_ingredients("I need tomato and onion for cooking")
201
+ "onion,tomato"
202
+
203
+ >>> get_ingredients("car house table")
204
+ ""
205
+
206
+ >>> get_ingredients("APPLE Carrot SUGAR")
207
+ "apple,carrot,sugar"
208
+ """
209
+ # Lists of common fruits, vegetables, and products
210
+ fruits = {
211
+ 'apple', 'banana', 'orange', 'strawberry', 'blueberry', 'raspberry',
212
+ 'mango', 'pineapple', 'grape', 'kiwi', 'peach', 'pear', 'plum',
213
+ 'cherry', 'lemon', 'lime', 'avocado', 'pomegranate', 'fig', 'date'
214
+ }
215
+
216
+ vegetables = {
217
+ 'carrot', 'broccoli', 'spinach', 'tomato', 'cucumber', 'lettuce',
218
+ 'onion', 'garlic', 'potato', 'sweet potato', 'zucchini', 'pepper',
219
+ 'eggplant', 'cauliflower', 'cabbage', 'kale', 'mushroom', 'celery'
220
+ }
221
+
222
+ products = {
223
+ 'vanilla', 'sugar', 'flour', 'salt', 'pepper', 'oil', 'butter',
224
+ 'milk', 'cream', 'cheese', 'yogurt', 'egg', 'honey', 'vinegar',
225
+ 'baking powder', 'baking soda', 'yeast', 'cinnamon', 'cocoa'
226
+ }
227
+
228
+ def is_ingredient(ingredient: str) -> bool:
229
+ return ingredient in fruits or ingredient in vegetables or ingredient in products
230
+
231
+ items = set([x.lower().strip() for x in item.split() if is_ingredient(x)])
232
+ return ','.join(sorted(items))
tools/youtube.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import backoff
2
+ from langchain_community.document_loaders import YoutubeLoader
3
+ from smolagents import tool
4
+
5
+ @tool
6
+ def load_youtube(video_url: str, phrase: str) -> str:
7
+ """
8
+ Load YouTube video content with customizable language and translation options.
9
+
10
+ This function retrieves the transcript and metadata from a YouTube video with retry logic
11
+ using exponential backoff for robust handling of temporary failures.
12
+
13
+ Args:
14
+ video_url (str): The YouTube video URL to load content from.
15
+ phrase (str): The phrase looking for in transcript.
16
+
17
+ Returns:
18
+ str: The loaded video content that occour after the looking phrase.
19
+
20
+ Raises:
21
+ Exception: Any exception that occurs after exhausting all retry attempts (max 3 tries).
22
+
23
+ Examples:
24
+ >>> load_youtube_with_options("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "Spanish transcript")
25
+ "Video content with transcript..."
26
+
27
+ "Spanish transcript translated to English..."
28
+ """
29
+ @backoff.on_exception(backoff.expo, Exception, max_tries=8, max_time=60)
30
+ def _loader(video_url) -> str:
31
+ loader = YoutubeLoader.from_youtube_url(video_url)
32
+ doc = loader.load()
33
+ if doc:
34
+ return doc[0].page_content.lower()
35
+ else:
36
+ raise Exception("Empty document")
37
+
38
+ phrase = phrase.replace(".", "").replace("?", "").lower()
39
+ content = _loader(video_url)
40
+ if phrase in content:
41
+ return content[content.index(phrase): len(content)]
42
+ return content