SriArun commited on
Commit
3a8719f
·
verified ·
1 Parent(s): 81917a3

Upload 9 files

Browse files
Files changed (9) hide show
  1. .env +1 -0
  2. agents.py +148 -0
  3. app.py +186 -12
  4. managed_agent.ipynb +289 -0
  5. poetry.lock +0 -0
  6. prompts.yaml +226 -0
  7. pyproject.toml +37 -0
  8. tools/final_answer.py +78 -0
  9. tools/tools.py +431 -0
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ GEMINI_KEY= "AIzaSyDa_pfQ9tdP64gITiGA0Mfnu7iS5VTzv0g"
agents.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import smolagents.models as sm_models
2
+
3
+ # _orig_roles = sm_models.MessageRole.roles
4
+
5
+ # @classmethod
6
+ # def _roles_with_control(cls):
7
+ # return _orig_roles() + ["control"]
8
+
9
+ # sm_models.MessageRole.roles = _roles_with_control
10
+
11
+
12
+
13
+ from smolagents import (CodeAgent,
14
+ GradioUI,
15
+ LiteLLMModel,
16
+ OpenAIServerModel,
17
+ ChatMessage,
18
+ ToolCallingAgent)
19
+ from smolagents.default_tools import (DuckDuckGoSearchTool,
20
+ VisitWebpageTool,
21
+ WikipediaSearchTool,
22
+ SpeechToTextTool,
23
+ PythonInterpreterTool)
24
+ import yaml
25
+ from tools.final_answer import FinalAnswerTool, check_reasoning, ensure_formatting
26
+ from tools.tools import (youtube_frames_to_images, use_vision_model,
27
+ read_file, download_file_from_url,
28
+ extract_text_from_image, analyze_csv_file,
29
+ analyze_excel_file, youtube_transcribe,
30
+ transcribe_audio, review_youtube_video)
31
+ import os
32
+ from dotenv import load_dotenv
33
+ import time
34
+
35
+ load_dotenv()
36
+
37
+ # Load prompts from YAML file
38
+ with open("prompts.yaml", 'r') as stream:
39
+ prompt_templates = yaml.safe_load(stream)
40
+
41
+
42
+ # class ThinkingLiteLLMModel(LiteLLMModel):
43
+ # def __init__(self, *args, **kwargs):
44
+ # # ensure the Litellm client also maps "control" → "control"
45
+ # cr = kwargs.pop("custom_role_conversions", {})
46
+ # cr["control"] = "control"
47
+ # super().__init__(*args, custom_role_conversions=cr, **kwargs)
48
+
49
+ # def __call__(self, messages, **kwargs) -> ChatMessage:
50
+ # NOTE: content must be a list of {type, text} dicts
51
+ # thinking_msg = {
52
+ # "role": "control",
53
+ # "content": [{"type": "text", "text": "thinking"}]
54
+ # }
55
+ # # prepend onto whatever messages the Agent built
56
+ # return super().__call__([thinking_msg] + messages, **kwargs)
57
+
58
+ class SlowLiteLLMModel(LiteLLMModel):
59
+ def __init__(self, *args, **kwargs):
60
+ super().__init__(*args, **kwargs)
61
+
62
+ def __call__(self, messages, **kwargs) -> ChatMessage:
63
+ time.sleep(15)
64
+ # prepend onto whatever messages the Agent built
65
+ return super().__call__(messages, **kwargs)
66
+
67
+ # # search_model_name = 'granite3.3:latest'
68
+ # search_model_name = 'cogito:14b'
69
+ # # search_model_name = 'qwen2:7b'
70
+ # search_model = ThinkingLiteLLMModel(model_id=f'ollama_chat/{search_model_name}',
71
+ # flatten_messages_as_text=True)
72
+
73
+ # web_agent = CodeAgent(
74
+ # model=search_model,
75
+ # tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), FinalAnswerTool()],
76
+ # max_steps=6,
77
+ # verbosity_level=1,
78
+ # grammar=None,
79
+ # planning_interval=6,
80
+ # name="web_agent",
81
+ # description="Searches the web using the and reviews web pages to find information.",
82
+ # additional_authorized_imports=['bs4', 'requests', 'io', 'wiki'],
83
+ # prompt_templates=prompt_templates
84
+ # )
85
+
86
+ # image_model_name = 'llama3.2-vision'
87
+ # image_model = OpenAIServerModel(model_id=image_model_name,
88
+ # api_base='http://localhost:11434/v1/',
89
+ # api_key='ollama',
90
+ # flatten_messages_as_text=False)
91
+ # image_agent = ToolCallingAgent(
92
+ # model=image_model,
93
+ # tools=[FinalAnswerTool()],
94
+ # max_steps=4,
95
+ # verbosity_level=2,
96
+ # grammar=None,
97
+ # planning_interval=6,
98
+ # #additional_authorized_imports=["PIL", "requests", "io", "numpy"],
99
+ # name="image_agent",
100
+ # description="Review images and videos for answers to questions based on visual data",
101
+ # prompt_templates=prompt_templates
102
+ # )
103
+
104
+ # react_model_name = 'qwen2:7b'
105
+ # # Initialize the chat model
106
+ # react_model = OpenAIServerModel(model_id=react_model_name,
107
+ # api_base='http://localhost:11434/v1/',
108
+ # api_key='ollama',
109
+ # flatten_messages_as_text=False)
110
+
111
+ react_model_name = "gemini/gemini-2.5-flash-preview-04-17"
112
+ react_model = LiteLLMModel(model_id=react_model_name,
113
+ api_key=os.getenv("GEMINI_KEY"),
114
+ temperature=0.2
115
+ )
116
+
117
+
118
+ manager_agent = CodeAgent(
119
+ model=react_model,
120
+ tools=[FinalAnswerTool(),
121
+ DuckDuckGoSearchTool(),
122
+ VisitWebpageTool(max_output_length=500000),
123
+ WikipediaSearchTool(extract_format='HTML'),
124
+ SpeechToTextTool(),
125
+ youtube_frames_to_images,
126
+ youtube_transcribe,
127
+ use_vision_model,
128
+ read_file, download_file_from_url,
129
+ extract_text_from_image,
130
+ analyze_csv_file, analyze_excel_file,
131
+ transcribe_audio,
132
+ review_youtube_video
133
+ ],
134
+ managed_agents=[],
135
+ additional_authorized_imports=['os', 'pandas', 'numpy', 'PIL', 'tempfile', 'PIL.Image'],
136
+ max_steps=20,
137
+ verbosity_level=1,
138
+ planning_interval=6,
139
+ name="Manager",
140
+ description="The manager of the team, responsible for overseeing and guiding the team's work.",
141
+ final_answer_checks=[check_reasoning, ensure_formatting],
142
+ prompt_templates=prompt_templates
143
+ )
144
+
145
+
146
+
147
+ if __name__ == "__main__":
148
+ GradioUI(manager_agent).launch()
app.py CHANGED
@@ -1,23 +1,163 @@
1
  import os
2
  import gradio as gr
3
  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
  """
@@ -45,7 +185,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
  # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
48
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
  print(agent_code)
50
 
51
  # 2. Fetch Questions
@@ -76,11 +216,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
76
  for item in questions_data:
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
 
79
  if not task_id or question_text is None:
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
82
  try:
83
- submitted_answer = agent(question_text)
 
 
 
 
84
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
  except Exception as e:
@@ -146,11 +291,9 @@ with gr.Blocks() as demo:
146
  gr.Markdown(
147
  """
148
  **Instructions:**
149
-
150
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
-
154
  ---
155
  **Disclaimers:**
156
  Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
@@ -171,7 +314,38 @@ with gr.Blocks() as demo:
171
  outputs=[status_output, results_table]
172
  )
173
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
175
  print("\n" + "-"*30 + " App Starting " + "-"*30)
176
  # Check for SPACE_HOST and SPACE_ID at startup for information
177
  space_host_startup = os.getenv("SPACE_HOST")
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
5
+ import os
6
+ from agents import manager_agent
7
+ from datetime import datetime
8
+ from typing import Optional
9
+ import time
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
 
 
15
  class BasicAgent:
16
  def __init__(self):
17
  print("BasicAgent initialized.")
18
+ self.agent = manager_agent
19
+ self.verbose = True
20
+
21
+ def __call__(self, question: str, files: list[str] = None) -> str:
22
+ print(f"Agent received question: {question[:50]}... with files: {files}")
23
+ result = self.answer_question(question, files)
24
+ print(f"Agent returning answer: {result}")
25
+ #time.sleep(60)
26
+ return result
27
+ def answer_question(self, question: str, task_file_path: Optional[str] = None) -> str:
28
+ """
29
+ Process a GAIA benchmark question and return the answer
30
+
31
+ Args:
32
+ question: The question to answer
33
+ task_file_path: Optional path to a file associated with the question
34
+
35
+ Returns:
36
+ The answer to the question
37
+ """
38
+ try:
39
+ if self.verbose:
40
+ print(f"Processing question: {question}")
41
+ if task_file_path:
42
+ print(f"With associated file: {task_file_path}")
43
+
44
+ # Create a context with file information if available
45
+ context = question
46
+
47
+ # If there's a file, read it and include its content in the context
48
+ if task_file_path:
49
+ try:
50
+ context = f"""
51
+ Question: {question}
52
+
53
+ This question has an associated file. You can download the file from
54
+ {DEFAULT_API_URL}/files/{task_file_path}
55
+ using the download_file_from_url tool.
56
+
57
+ Analyze the file content above to answer the question.
58
+ """
59
+ except Exception as file_e:
60
+ context = f"""
61
+ Question: {question}
62
+
63
+ This question has an associated file at path: {task_file_path}
64
+ However, there was an error reading the file: {file_e}
65
+ You can still try to answer the question based on the information provided.
66
+ """
67
+
68
+ # Check for special cases that need specific formatting
69
+ # Reversed text questions
70
+ if question.startswith(".") or ".rewsna eht sa" in question:
71
+ context = f"""
72
+ This question appears to be in reversed text. Here's the reversed version:
73
+ {question[::-1]}
74
+
75
+ Now answer the question above. Remember to format your answer exactly as requested.
76
+ """
77
+
78
+ # Add a prompt to ensure precise answers
79
+ full_prompt = f"""{context}
80
+
81
+ When answering, provide ONLY the precise answer requested.
82
+ Do not include explanations, steps, reasoning, or additional text.
83
+ Be direct and specific. GAIA benchmark requires exact matching answers.
84
+ For example, if asked "What is the capital of France?", respond simply with "Paris".
85
+ """
86
+
87
+ # Run the agent with the question
88
+ answer = self.agent.run(full_prompt)
89
+
90
+ # Clean up the answer to ensure it's in the expected format
91
+ # Remove common prefixes that models often add
92
+ answer = self._clean_answer(answer)
93
+
94
+ if self.verbose:
95
+ print(f"Generated answer: {answer}")
96
+
97
+ return answer
98
+ except Exception as e:
99
+ error_msg = f"Error answering question: {e}"
100
+ if self.verbose:
101
+ print(error_msg)
102
+ return error_msg
103
+
104
+ def _clean_answer(self, answer: any) -> str:
105
+ """
106
+ Clean up the answer to remove common prefixes and formatting
107
+ that models often add but that can cause exact match failures.
108
+
109
+ Args:
110
+ answer: The raw answer from the model
111
+
112
+ Returns:
113
+ The cleaned answer as a string
114
+ """
115
+ # Convert non-string types to strings
116
+ if not isinstance(answer, str):
117
+ # Handle numeric types (float, int)
118
+ if isinstance(answer, float):
119
+ # Format floating point numbers properly
120
+ # Check if it's an integer value in float form (e.g., 12.0)
121
+ if answer.is_integer():
122
+ formatted_answer = str(int(answer))
123
+ else:
124
+ # For currency values that might need formatting
125
+ if abs(answer) >= 1000:
126
+ formatted_answer = f"${answer:,.2f}"
127
+ else:
128
+ formatted_answer = str(answer)
129
+ return formatted_answer
130
+ elif isinstance(answer, int):
131
+ return str(answer)
132
+ else:
133
+ # For any other type
134
+ return str(answer)
135
+
136
+ # Now we know answer is a string, so we can safely use string methods
137
+ # Normalize whitespace
138
+ answer = answer.strip()
139
+
140
+ # Remove common prefixes and formatting that models add
141
+ prefixes_to_remove = [
142
+ "The answer is ",
143
+ "Answer: ",
144
+ "Final answer: ",
145
+ "The result is ",
146
+ "To answer this question: ",
147
+ "Based on the information provided, ",
148
+ "According to the information: ",
149
+ ]
150
+
151
+ for prefix in prefixes_to_remove:
152
+ if answer.startswith(prefix):
153
+ answer = answer[len(prefix):].strip()
154
+
155
+ # Remove quotes if they wrap the entire answer
156
+ if (answer.startswith('"') and answer.endswith('"')) or (answer.startswith("'") and answer.endswith("'")):
157
+ answer = answer[1:-1].strip()
158
+
159
+ return answer
160
+
161
 
162
  def run_and_submit_all( profile: gr.OAuthProfile | None):
163
  """
 
185
  print(f"Error instantiating agent: {e}")
186
  return f"Error initializing agent: {e}", None
187
  # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
188
+ agent_code = f"https://github.com/ssgrummons/huggingface_final_assignment"
189
  print(agent_code)
190
 
191
  # 2. Fetch Questions
 
216
  for item in questions_data:
217
  task_id = item.get("task_id")
218
  question_text = item.get("question")
219
+ files = item.get("file_name")
220
  if not task_id or question_text is None:
221
  print(f"Skipping item with missing task_id or question: {item}")
222
  continue
223
  try:
224
+ if files is None or files == '':
225
+ print(files)
226
+ submitted_answer = agent(question_text)
227
+ else:
228
+ submitted_answer = agent(question_text, task_id)
229
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
230
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
231
  except Exception as e:
 
291
  gr.Markdown(
292
  """
293
  **Instructions:**
 
294
  1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
295
  2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
296
  3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
 
297
  ---
298
  **Disclaimers:**
299
  Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
 
314
  outputs=[status_output, results_table]
315
  )
316
 
317
+ import sys
318
+ from pathlib import Path
319
+
320
+ class Tee:
321
+ def __init__(self, file_path):
322
+ log_path = Path(file_path)
323
+ log_path.parent.mkdir(parents=True, exist_ok=True)
324
+ self.terminal_stdout = sys.__stdout__
325
+ self.terminal_stderr = sys.__stderr__
326
+ self.log = open(log_path, "a")
327
+
328
+ def write(self, message):
329
+ self.terminal_stdout.write(message)
330
+ self.log.write(message)
331
+
332
+ def flush(self):
333
+ self.terminal_stdout.flush()
334
+ self.log.flush()
335
+
336
+ def isatty(self):
337
+ return self.terminal_stdout.isatty()
338
+
339
+
340
  if __name__ == "__main__":
341
+
342
+ # Redirect stdout and stderr
343
+ log_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
344
+ log_file = f"./logs/output_{log_timestamp}.log"
345
+ tee = Tee(log_file)
346
+ sys.stdout = tee
347
+ sys.stderr = tee
348
+
349
  print("\n" + "-"*30 + " App Starting " + "-"*30)
350
  # Check for SPACE_HOST and SPACE_ID at startup for information
351
  space_host_startup = os.getenv("SPACE_HOST")
managed_agent.ipynb ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "674fa1cc",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Testing Agent Components\n",
9
+ "\n",
10
+ "I used this notebook to test different tools and components. "
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "code",
15
+ "execution_count": null,
16
+ "id": "88eccfb3",
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "from agents import manager_agent\n",
21
+ "manager_agent.visualize()"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": null,
27
+ "id": "e1925d1f",
28
+ "metadata": {},
29
+ "outputs": [],
30
+ "source": [
31
+ "from PIL import Image\n",
32
+ "\n",
33
+ "#manager_agent.run(\"How many bird species are in this image?\", images=images)\n",
34
+ "manager_agent.run(\"In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?\")"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "execution_count": null,
40
+ "id": "1c904403",
41
+ "metadata": {},
42
+ "outputs": [],
43
+ "source": [
44
+ "manager_agent.run('How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.')"
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "execution_count": null,
50
+ "id": "ca93462b",
51
+ "metadata": {},
52
+ "outputs": [],
53
+ "source": [
54
+ "DEFAULT_API_URL = \"https://agents-course-unit4-scoring.hf.space\"\n",
55
+ "question = \"What is the final numeric output from the attached Python code?\"\n",
56
+ "task_file_path = \"f918266a-b3e0-4914-865d-4faa564f1aef\"\n",
57
+ "filename = \"f918266a-b3e0-4914-865d-4faa564f1aef.py\"\n",
58
+ "context = f\"\"\"\n",
59
+ "Here is the question you need to answer: {question}\n",
60
+ "\n",
61
+ "This question has an associated file. You can download the file from \n",
62
+ "{DEFAULT_API_URL}/files/{task_file_path}\n",
63
+ "using the download_file_from_url tool and name it {filename}. \n",
64
+ "After downloading the file, use the save_and_read_file tool to read the contents of the file.\n",
65
+ "\n",
66
+ "Come up with a plan to analyze the file content above to answer the question. Execute that plan carefully and stay focused.\n",
67
+ "\"\"\"\n",
68
+ "full_prompt = f\"\"\"{context}\n",
69
+ "\n",
70
+ "When answering, provide ONLY the precise answer requested. \n",
71
+ "Do not include explanations, steps, reasoning, or additional text.\n",
72
+ "Be direct and specific. GAIA benchmark requires exact matching answers.\n",
73
+ "For example, if asked \"What is the capital of France?\", respond simply with \"Paris\".\n",
74
+ "\"\"\"\n",
75
+ "manager_agent.run(context)"
76
+ ]
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "execution_count": null,
81
+ "id": "4e9bf1e6",
82
+ "metadata": {},
83
+ "outputs": [],
84
+ "source": [
85
+ "DEFAULT_API_URL = \"https://agents-course-unit4-scoring.hf.space\"\n",
86
+ "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 :(Could 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.\"\n",
87
+ "task_file_path = \"1f975693-876d-457b-a649-393859e79bf3\"\n",
88
+ "filename = \"1f975693-876d-457b-a649-393859e79bf3.mp3\"\n",
89
+ "context = f\"\"\"\n",
90
+ "Here is the question you need to answer: {question}\n",
91
+ "\n",
92
+ "This question has an associated file. You can download the file from \n",
93
+ "{DEFAULT_API_URL}/files/{task_file_path}\n",
94
+ "using the download_file_from_url tool and name it {filename}. \n",
95
+ "After downloading the file, use the save_and_read_file tool to read the contents of the file.\n",
96
+ "\n",
97
+ "Come up with a plan to analyze the file content above to answer the question. Execute that plan carefully and stay focused.\n",
98
+ "\"\"\"\n",
99
+ "full_prompt = f\"\"\"{context}\n",
100
+ "\n",
101
+ "When answering, provide ONLY the precise answer requested. \n",
102
+ "Do not include explanations, steps, reasoning, or additional text.\n",
103
+ "Be direct and specific. GAIA benchmark requires exact matching answers.\n",
104
+ "For example, if asked \"What is the capital of France?\", respond simply with \"Paris\".\n",
105
+ "\"\"\"\n",
106
+ "manager_agent.run(context)"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "execution_count": null,
112
+ "id": "8bf3f8eb",
113
+ "metadata": {},
114
+ "outputs": [],
115
+ "source": [
116
+ "DEFAULT_API_URL = \"https://agents-course-unit4-scoring.hf.space\"\n",
117
+ "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.\"\n",
118
+ "task_file_path = \"7bd855d8-463d-4ed5-93ca-5fe35145f733\"\n",
119
+ "filename = \"7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx\"\n",
120
+ "context = f\"\"\"\n",
121
+ "Here is the question you need to answer: {question}\n",
122
+ "\n",
123
+ "This question has an associated file. You can download the file from \n",
124
+ "{DEFAULT_API_URL}/files/{task_file_path}\n",
125
+ "using the download_file_from_url tool and name it {filename}. \n",
126
+ "After downloading the file, use the save_and_read_file tool to read the contents of the file.\n",
127
+ "\n",
128
+ "Come up with a plan to analyze the file content above to answer the question. Execute that plan carefully and stay focused.\n",
129
+ "\"\"\"\n",
130
+ "full_prompt = f\"\"\"{context}\n",
131
+ "\n",
132
+ "When answering, provide ONLY the precise answer requested. \n",
133
+ "Do not include explanations, steps, reasoning, or additional text.\n",
134
+ "Be direct and specific. GAIA benchmark requires exact matching answers.\n",
135
+ "For example, if asked \"What is the capital of France?\", respond simply with \"Paris\".\n",
136
+ "\"\"\"\n",
137
+ "manager_agent.run(context)"
138
+ ]
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "execution_count": null,
143
+ "id": "51a53c63",
144
+ "metadata": {},
145
+ "outputs": [],
146
+ "source": [
147
+ "manager_agent.run(\"How many r's are in the word Strawberry?\")\n"
148
+ ]
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "execution_count": null,
153
+ "id": "d45cd981",
154
+ "metadata": {},
155
+ "outputs": [],
156
+ "source": [
157
+ "from tools.tools import youtube_frames_to_images\n",
158
+ "results = youtube_frames_to_images('https://youtube.com/watch?v=L1vXCYZAYYM')"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "execution_count": null,
164
+ "id": "9d806dfe",
165
+ "metadata": {},
166
+ "outputs": [],
167
+ "source": [
168
+ "from tools.tools import youtube_transcribe\n",
169
+ "results = youtube_transcribe('https://www.youtube.com/watch?v=1htKBjuUWec')\n",
170
+ "print(results)"
171
+ ]
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "execution_count": null,
176
+ "id": "b87ee5e6",
177
+ "metadata": {},
178
+ "outputs": [],
179
+ "source": [
180
+ "from PIL import Image\n",
181
+ "from os import walk, path\n",
182
+ "\n",
183
+ "# Path to image file\n",
184
+ "picture_path = './images'\n",
185
+ "\n",
186
+ "# List to hold images\n",
187
+ "images = []\n",
188
+ "\n",
189
+ "# Walk through the directory and get all .png files paths\n",
190
+ "for root, dirs, files in walk(picture_path):\n",
191
+ " for file in files:\n",
192
+ " if file.endswith('.png'):\n",
193
+ " # Construct full path of each png file\n",
194
+ " picture_file = path.join(root, file)\n",
195
+ " \n",
196
+ " try:\n",
197
+ " # Open image from path\n",
198
+ " img = Image.open(picture_file)\n",
199
+ " \n",
200
+ " # Append it to the list of images after converting it to RGB format\n",
201
+ " images.append(img.convert('RGB'))\n",
202
+ " except IOError as e:\n",
203
+ " print(f'Error opening {picture_file}: {e}')\n",
204
+ " continue\n",
205
+ "\n",
206
+ "\n",
207
+ "from tools.tools import use_vision_model\n",
208
+ "\n",
209
+ "query = \"Review these pictures. What is the highest number of bird species to appear in the same photo of these photos?\"\n",
210
+ "\n",
211
+ "tool_input = {\n",
212
+ " \"question\": query,\n",
213
+ " \"images\": images\n",
214
+ "}\n",
215
+ "\n",
216
+ "use_vision_model(**tool_input)"
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "execution_count": null,
222
+ "id": "5f294f90",
223
+ "metadata": {},
224
+ "outputs": [],
225
+ "source": [
226
+ "from tools.tools import download_file_from_url, transcribe_audio\n",
227
+ "\n",
228
+ "task_file_path = \"1f975693-876d-457b-a649-393859e79bf3\"\n",
229
+ "filename = \"1f975693-876d-457b-a649-393859e79bf3.mp3\"\n",
230
+ "url = f'{DEFAULT_API_URL}/files/{task_file_path}'\n",
231
+ "\n",
232
+ "tool_input = {\"url\": url}\n",
233
+ "\n",
234
+ "filename = download_file_from_url(**tool_input).strip(\"File downloaded to \").strip(\". You can now process this file.'\")\n",
235
+ "\n",
236
+ "tool_input = {\"audio_file_path\": filename}\n",
237
+ "\n",
238
+ "transcribe_audio(**tool_input)"
239
+ ]
240
+ },
241
+ {
242
+ "cell_type": "code",
243
+ "execution_count": null,
244
+ "id": "b34b7bf2",
245
+ "metadata": {},
246
+ "outputs": [],
247
+ "source": [
248
+ "from tools.tools import read_file, download_file_from_url\n",
249
+ "\n",
250
+ "DEFAULT_API_URL = \"https://agents-course-unit4-scoring.hf.space\"\n",
251
+ "taskid = \"f918266a-b3e0-4914-865d-4faa564f1aef\"\n",
252
+ "filename = f\"{taskid}.py\"\n",
253
+ "url = f'{DEFAULT_API_URL}/files/{taskid}'\n",
254
+ "\n",
255
+ "tool_input = {\"url\": url, \"filename\": filename}\n",
256
+ "\n",
257
+ "filepath = download_file_from_url(**tool_input).strip(\"File downloaded to \").strip(\". You can now process this file.'\")\n",
258
+ "\n",
259
+ "\n",
260
+ "tool_input = {\"filepath\": filepath}\n",
261
+ "\n",
262
+ "output = read_file(**tool_input)\n",
263
+ "\n",
264
+ "print(output)"
265
+ ]
266
+ }
267
+ ],
268
+ "metadata": {
269
+ "kernelspec": {
270
+ "display_name": ".venv (3.12.6)",
271
+ "language": "python",
272
+ "name": "python3"
273
+ },
274
+ "language_info": {
275
+ "codemirror_mode": {
276
+ "name": "ipython",
277
+ "version": 3
278
+ },
279
+ "file_extension": ".py",
280
+ "mimetype": "text/x-python",
281
+ "name": "python",
282
+ "nbconvert_exporter": "python",
283
+ "pygments_lexer": "ipython3",
284
+ "version": "3.12.6"
285
+ }
286
+ },
287
+ "nbformat": 4,
288
+ "nbformat_minor": 5
289
+ }
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
prompts.yaml ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "system_prompt": |-
2
+ You are an expert assistant named who can solve assigned tasks using code blobs. You will be given a task to solve as best you can.
3
+ You do not always have to use code to solve the task. If you can solve the tasks without using code blobs, do that.
4
+ To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
5
+ To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
6
+
7
+ At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
8
+ Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
9
+ During each intermediate step, you can use 'print()' to save whatever important information you will then need.
10
+ These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
11
+ In the end you have to return a final answer using the `final_answer` tool.
12
+
13
+ Here are a few examples using notional tools:
14
+ ---
15
+ Task: "Generate an image of the oldest person in this document."
16
+
17
+ Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
18
+ Code:
19
+ ```py
20
+ answer = document_qa(document=document, question="Who is the oldest person mentioned?")
21
+ print(answer)
22
+ ```<end_code>
23
+ Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
24
+
25
+ Thought: I will now generate an image showcasing the oldest person.
26
+ Code:
27
+ ```py
28
+ image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
29
+ final_answer(image)
30
+ ```<end_code>
31
+
32
+ ---
33
+ Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
34
+
35
+ Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
36
+ Code:
37
+ ```py
38
+ result = 5 + 3 + 1294.678
39
+ final_answer(result)
40
+ ```<end_code>
41
+
42
+ Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools:
43
+ {%- for tool in tools.values() %}
44
+ - {{ tool.name }}: {{ tool.description }}
45
+ Takes inputs: {{tool.inputs}}
46
+ Returns an output of type: {{tool.output_type}}
47
+ {%- endfor %}
48
+
49
+ Use your web_search tool when you want to get Google search results.
50
+ Use your wikipedia_search tool when you want to return entire articles from Wikipedia.
51
+ Use your visit_webpage tool when you want to retrieve content from a webpage.
52
+
53
+ Be thorough in your research. When researching a topic, do both a web search and a wikipedia search.
54
+ Visit the web pages you find in relevant reference links.
55
+
56
+ Here are the rules you should always follow to solve your task:
57
+ 1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
58
+ 2. Use only variables that you have defined!
59
+ 3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
60
+ 4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
61
+ 5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
62
+ 6. Never name a variable the same name as a tool. Never name a variable 'final_answer'.
63
+ 7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
64
+ 8. You can use imports in your code, but only from the following list of modules: {% if authorized_imports is defined and authorized_imports %} {{ authorized_imports }} {% endif %}
65
+ 9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
66
+ 10. Don't give up! You're in charge of solving the task, not just providing directions to solve it.
67
+
68
+ Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
69
+ "planning":
70
+ "initial_facts": |-
71
+ Below I will present you a task.
72
+ You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
73
+ To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
74
+ Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
75
+
76
+ ---
77
+ ### 1. Facts given in the task
78
+ List here the specific facts given in the task that could help you (there might be nothing here).
79
+
80
+ ### 2. Facts to look up
81
+ List here any facts that we may need to look up.
82
+ Also list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.
83
+
84
+ ### 3. Facts to derive
85
+ List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
86
+
87
+ Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
88
+ ### 1. Facts given in the task
89
+ ### 2. Facts to look up
90
+ ### 3. Facts to derive
91
+ Do not add anything else.
92
+
93
+ Here is the task:
94
+ ```
95
+ {{task}}
96
+ ```
97
+ Now begin!
98
+ "initial_plan": |-
99
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
100
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
101
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
102
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
103
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
104
+
105
+ Here is your task:
106
+
107
+ Task:
108
+ ```
109
+ {{task}}
110
+ ```
111
+ You can leverage these tools:
112
+ {%- for tool in tools.values() %}
113
+ - {{ tool.name }}: {{ tool.description }}
114
+ Takes inputs: {{tool.inputs}}
115
+ Returns an output of type: {{tool.output_type}}
116
+ {%- endfor %}
117
+
118
+ {%- if managed_agents and managed_agents.values() | list %}
119
+ You can also give tasks to team members.
120
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.
121
+ Given that this team member is a real human, you should be very verbose in your request.
122
+ Here is a list of the team members that you can call:
123
+ {%- for agent in managed_agents.values() %}
124
+ - {{ agent.name }}: {{ agent.description }}
125
+ {%- endfor %}
126
+ {%- else %}
127
+ {%- endif %}
128
+
129
+ Now begin! Write your plan below.
130
+ "update_facts_pre_messages": |-
131
+ You are a world expert at gathering known and unknown facts based on a conversation.
132
+ Below you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:
133
+ ### 1. Facts given in the task
134
+ ### 2. Facts that we have learned
135
+ ### 3. Facts still to look up
136
+ ### 4. Facts still to derive
137
+ Find the task and history below:
138
+
139
+ You have been given a task:
140
+ ```
141
+ {{task}}
142
+ ```
143
+
144
+ "update_facts_post_messages": |-
145
+ Earlier we've built a list of facts.
146
+ But since in your previous steps you may have learned useful new facts or invalidated some false ones.
147
+ Please update your list of facts based on the previous history, and provide these headings:
148
+ ### 1. Facts given in the task
149
+ ### 2. Facts that we have learned
150
+ ### 3. Facts still to look up
151
+ ### 4. Facts still to derive
152
+ Now write your new list of facts below.
153
+ "update_plan_pre_messages": |-
154
+ You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
155
+ You have been given a task:
156
+ ```
157
+ {{task}}
158
+ ```
159
+
160
+ Find below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.
161
+ If the previous tries so far have met some success, you can make an updated plan based on these actions.
162
+ If you are stalled, you can make a completely new plan starting from scratch.
163
+ "update_plan_post_messages": |-
164
+ You're still working towards solving this task:
165
+ ```
166
+ {{task}}
167
+ ```
168
+ You can leverage these tools:
169
+ {%- for tool in tools.values() %}
170
+ - {{ tool.name }}: {{ tool.description }}
171
+ Takes inputs: {{tool.inputs}}
172
+ Returns an output of type: {{tool.output_type}}
173
+ {%- endfor %}
174
+
175
+ {%- if managed_agents and managed_agents.values() | list %}
176
+ You can also give tasks to team members.
177
+ Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
178
+ Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
179
+ Here is a list of the team members that you can call:
180
+ {%- for agent in managed_agents.values() %}
181
+ - {{ agent.name }}: {{ agent.description }}
182
+ {%- endfor %}
183
+ {%- else %}
184
+ {%- endif %}
185
+
186
+
187
+ Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
188
+ This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
189
+ Beware that you have {remaining_steps} steps remaining.
190
+ Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
191
+ After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
192
+
193
+ Now write your new plan below.
194
+ "managed_agent":
195
+ "task": |-
196
+ You're a helpful agent named '{{name}}'.
197
+ You have been submitted this task by your manager:
198
+ ---
199
+ Task:
200
+ {{task}}
201
+ ---
202
+ You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.
203
+ Your final_answer WILL HAVE to contain these parts:
204
+ ### 1. Task outcome (short version):
205
+ ### 2. Task outcome (extremely detailed version):
206
+ ### 3. Additional context (if relevant):
207
+
208
+ Ensure all the information relevant to the task you were given is provided in your final_answer. You will be rewarded based on how much relevant information you can provide, the more comprehensive the better.
209
+ Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
210
+ And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
211
+ "report": |-
212
+ Here is the final answer from your managed agent '{{name}}':
213
+ {{final_answer}}
214
+ "final_answer":
215
+ "pre_messages": |-
216
+ An agent tried to answer a user query but it got stuck and failed to do so. You are tasked with providing an answer instead. Here is the agent's memory:
217
+ "post_messages": |-
218
+ Based on the above, please provide an answer to the following user request:
219
+ {{task}}
220
+ You are to provide your answer with the following template: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
221
+ Do no include any brackets in your final answer.
222
+ If you are asked for a number, don't use commas to write your number. Don't use units such as $ or percent sign unless specified otherwise. Write your number in Arabic numbers (such as 9 or 3 or 1093) unless specified otherwise.
223
+ If you are asked for a currency in your answer, use the symbol for that currency. For example, if you are asked for the answers in USD, an example answer would be $40.00
224
+ If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
225
+ If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
226
+ If you are asked for a comma separated list, ensure you only return the content of that list, and NOT the brackets '[]'
pyproject.toml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "huggingface-final-assignment"
3
+ version = "0.1.0"
4
+ description = "Final Assignment for Hugging Face AI Agents Course"
5
+ authors = ["Samuel Grummons <samuel.grummons@gmail.com>"]
6
+ readme = "README.md"
7
+
8
+ [tool.poetry.dependencies]
9
+ python = "3.12.6"
10
+ smolagents = {extras = ["transformers"], version = "^1.14.0"}
11
+ pytz = "^2025.2"
12
+ gradio = "^5.26.0"
13
+ litellm = "^1.67.2"
14
+ gradiologin = "^0.1.0"
15
+ helium = "^5.1.1"
16
+ selenium = "^4.31.0"
17
+ imageio = {extras = ["ffmpeg"], version = "^2.37.0"}
18
+ pytesseract = "^0.3.13"
19
+ duckduckgo-search = "^8.0.1"
20
+ markdownify = "^1.1.0"
21
+ pytube = "^15.0.0"
22
+ pillow = "^11.2.1"
23
+ yt-dlp = "^2025.3.31"
24
+ wikipedia-api = "^0.8.1"
25
+ transformers = "^4.51.3"
26
+ openai-whisper = "^20240930"
27
+ pandas = "^2.2.3"
28
+ openpyxl = "^3.1.5"
29
+ google-genai = "^1.12.1"
30
+
31
+
32
+ [tool.poetry.group.dev.dependencies]
33
+ ipywidgets = "^8.1.6"
34
+
35
+ [build-system]
36
+ requires = ["poetry-core"]
37
+ build-backend = "poetry.core.masonry.api"
tools/final_answer.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ from smolagents.tools import Tool
3
+ from smolagents import LiteLLMModel
4
+
5
+ class FinalAnswerTool(Tool):
6
+ name = "final_answer"
7
+ description = "Used to submit the final answer to the problem."
8
+ inputs = {'answer': {'type': 'any', 'description': 'The final answer to the problem'}}
9
+ output_type = "any"
10
+
11
+ def forward(self, answer: Any) -> Any:
12
+ return answer
13
+
14
+ def __init__(self, *args, **kwargs):
15
+ self.is_initialized = False
16
+
17
+
18
+ def check_reasoning(final_answer, agent_memory):
19
+ model_name = 'cogito:14b'
20
+ multimodal_model = LiteLLMModel(model_id=f'ollama_chat/{model_name}')
21
+ prompt = f"""
22
+ Here is a user-given task and the agent steps: {agent_memory.get_succinct_steps()}. Now here is the answer that was given:
23
+ {final_answer}
24
+ Please check that the reasoning process and results are correct: do they correctly answer the given task?
25
+ First list reasons why yes/no, then write your final decision: PASS in caps lock if it is satisfactory, FAIL if it is not.
26
+ Be reasonably strict. You are being graded on your ability to provide the right answer. You should have >90% confidence that the answer is correct.
27
+ """
28
+ messages = [
29
+ {
30
+ "role": "user",
31
+ "content": [
32
+ {
33
+ "type": "text",
34
+ "text": prompt,
35
+ }
36
+ ]
37
+ }
38
+ ]
39
+ output = multimodal_model(messages).content
40
+ print("Feedback: ", output)
41
+ if "FAIL" in output:
42
+ raise Exception(output)
43
+ return True
44
+
45
+ def ensure_formatting(final_answer, agent_memory):
46
+ # Ensure the final answer is formatted correctly
47
+ model_name = 'granite3.3:8b'
48
+ # Initialize the chat model
49
+ model = LiteLLMModel(model_id=f'ollama_chat/{model_name}',
50
+ flatten_messages_as_text=True)
51
+ prompt = f"""
52
+ Here is a user-given task and the agent steps: {agent_memory.get_succinct_steps()}. Now here is the FINAL ANSWER that was given:
53
+ {final_answer}
54
+ Ensure the FINAL ANSWER is in the right format as asked for by the task. Here are the instructions that you need to evaluate:
55
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
56
+ If you are asked for a number, don't use commas to write your number. Don't use units such as $ or percent sign unless specified otherwise. Write your number in Arabic numbers (such as 9 or 3 or 1093) unless specified otherwise.
57
+ If you are asked for a currency in your answer, use the symbol for that currency. For example, if you are asked for the answers in USD, an example answer would be $40.00
58
+ If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
59
+ If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
60
+ If you are asked for a comma separated list, ensure you only return the content of that list, and NOT the brackets '[]'
61
+ First list reasons why it is/is not in the correct format and then write your final decision: PASS in caps lock if it is satisfactory, FAIL if it is not.
62
+ """
63
+ messages = [
64
+ {
65
+ "role": "user",
66
+ "content": [
67
+ {
68
+ "type": "text",
69
+ "text": prompt,
70
+ }
71
+ ]
72
+ }
73
+ ]
74
+ output = model(messages).content
75
+ print("Feedback: ", output)
76
+ if "FAIL" in output:
77
+ raise Exception(output)
78
+ return True
tools/tools.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import requests
3
+ import os
4
+
5
+ from time import sleep
6
+ from urllib.parse import urlparse
7
+ from typing import Optional, List
8
+ import yt_dlp
9
+ import imageio
10
+ from google.genai import types
11
+
12
+ from PIL import Image
13
+ from smolagents import CodeAgent, tool, OpenAIServerModel, LiteLLMModel
14
+ from google import genai
15
+ from dotenv import load_dotenv
16
+
17
+ load_dotenv()
18
+
19
+ # def save_screenshot(memory_step: ActionStep, agent: CodeAgent) -> None:
20
+ # sleep(1.0) # Let JavaScript animations happen before taking the screenshot
21
+ # driver = helium.get_driver()
22
+ # current_step = memory_step.step_number
23
+ # if driver is not None:
24
+ # for previous_memory_step in agent.memory.steps: # Remove previous screenshots from logs for lean processing
25
+ # if isinstance(previous_memory_step, ActionStep) and previous_memory_step.step_number <= current_step - 2:
26
+ # previous_memory_step.observations_images = None
27
+ # png_bytes = driver.get_screenshot_as_png()
28
+ # image = Image.open(BytesIO(png_bytes))
29
+ # print(f"Captured a browser screenshot: {image.size} pixels")
30
+ # memory_step.observations_images = [image.copy()] # Create a copy to ensure it persists, important!
31
+
32
+ # # Update observations with current URL
33
+ # url_info = f"Current url: {driver.current_url}"
34
+ # memory_step.observations = (
35
+ # url_info if memory_step.observations is None else memory_step.observations + "\n" + url_info
36
+ # )
37
+ # return
38
+
39
+ # def initialize_driver():
40
+ # """Initialize the Selenium WebDriver."""
41
+ # chrome_options = webdriver.ChromeOptions()
42
+ # chrome_options.add_argument("--force-device-scale-factor=1")
43
+ # chrome_options.add_argument("--window-size=1000,1350")
44
+ # chrome_options.add_argument("--disable-pdf-viewer")
45
+ # chrome_options.add_argument("--window-position=0,0")
46
+ # return helium.start_chrome(headless=False, options=chrome_options)
47
+
48
+ # @tool
49
+ # def search_item_ctrl_f(text: str, nth_result: int = 1) -> str:
50
+ # """
51
+ # Searches for text on the current page via Ctrl + F and jumps to the nth occurrence.
52
+ # Args:
53
+ # text: The text to search for
54
+ # nth_result: Which occurrence to jump to (default: 1)
55
+ # """
56
+ # elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]")
57
+ # if nth_result > len(elements):
58
+ # raise Exception(f"Match n°{nth_result} not found (only {len(elements)} matches found)")
59
+ # result = f"Found {len(elements)} matches for '{text}'."
60
+ # elem = elements[nth_result - 1]
61
+ # driver.execute_script("arguments[0].scrollIntoView(true);", elem)
62
+ # result += f"Focused on element {nth_result} of {len(elements)}"
63
+ # return result
64
+
65
+
66
+ # @tool
67
+ # def go_back() -> None:
68
+ # """Used when navigating web pages using Helium. Goes back to previous page."""
69
+ # driver.back()
70
+
71
+
72
+ # @tool
73
+ # def close_popups() -> str:
74
+ # """
75
+ # Closes any visible modal or pop-up on the page. Use this to dismiss pop-up windows! This does not work on cookie consent banners.
76
+ # """
77
+ # webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
78
+
79
+ @tool
80
+ def use_vision_model(question: str, images: List[Image.Image]) -> str:
81
+ """
82
+ Use a Vision Model to answer a question about a set of images.
83
+ Always use this tool to ask questions about a set of images you have been provided.
84
+ This function uses an image-to-text AI model.
85
+ You can ask a question about a list of one image or a list of multiple images.
86
+ So, if you have multiple images that you want to ask the same question of, pass the entire list of images to the model.
87
+ Ensure your prompt is specific enough to retrieve the exact information you are looking for.
88
+
89
+ Args:
90
+ question: The question to ask about the images. Type: str
91
+ images: The list of images to as the question about. Type: List[PIL.Image.Image]
92
+ """
93
+ image_model_name = "gemini/gemini-1.5-flash"
94
+
95
+ print(f'Leveraging model {image_model_name}')
96
+ # image_model_name = 'gemma3:12b'
97
+ # image_model = OpenAIServerModel(
98
+ # model_id=image_model_name,
99
+ # api_base='http://localhost:11434/v1/',
100
+ # api_key='ollama',
101
+ # flatten_messages_as_text=False
102
+ # )
103
+ image_model =LiteLLMModel(model_id=image_model_name,
104
+ api_key=os.getenv("GEMINI_KEY"),
105
+ temperature=0.2
106
+ )
107
+
108
+ content = [
109
+ {
110
+ "type": "text",
111
+ "text": question
112
+ }
113
+ ]
114
+ print(f"Asking model a question about {len(images)} images")
115
+ for image in images:
116
+ content.append({
117
+ "type": "image",
118
+ "image": image # ✅ Directly the PIL Image, no wrapping
119
+ })
120
+
121
+ messages = [
122
+ {
123
+ "role": "user",
124
+ "content": content
125
+ }
126
+ ]
127
+
128
+ output = image_model(messages).content
129
+ print(f'Model returned: {output}')
130
+ return output
131
+
132
+ @tool
133
+ def review_youtube_video(url: str, question: str) -> str:
134
+ """
135
+ Reviews a YouTube video and answers a specific question about that video.
136
+
137
+ Args:
138
+ url (str): the URL to the YouTube video. Should be like this format: https://www.youtube.com/watch?v=9hE5-98ZeCg
139
+ question (str): The question you are asking about the video
140
+ """
141
+ try:
142
+ client = genai.Client(api_key=os.getenv('GEMINI_KEY'))
143
+ model = 'gemini-2.0-flash-lite'
144
+ response = client.models.generate_content(
145
+ model=model,
146
+ contents=types.Content(
147
+ parts=[
148
+ types.Part(
149
+ file_data=types.FileData(file_uri=url)
150
+ ),
151
+ types.Part(text=question)
152
+ ]
153
+ )
154
+ )
155
+ return response.text
156
+ except Exception as e:
157
+ return f"Error asking {model} about video: {str(e)}"
158
+
159
+ @tool
160
+ def youtube_frames_to_images(url: str, sample_interval_seconds: int = 5) -> List[Image.Image]:
161
+ """
162
+ Reviews a YouTube video and returns a List of PIL Images (List[PIL.Image.Image]), which can then be reviewed by a vision model.
163
+ Only use this tool if you have been given a YouTube video that you need to analyze.
164
+ This will generate a list of images, and you can use the use_vision_model tool to analyze those images
165
+ Args:
166
+ url: The Youtube URL
167
+ sample_interval_seconds: The sampling interval (default is 5 seconds)
168
+ """
169
+ with tempfile.TemporaryDirectory() as tmpdir:
170
+ # Download the video locally
171
+ ydl_opts = {
172
+ 'format': 'bestvideo[height<=1080]+bestaudio/best[height<=1080]/best',
173
+ 'outtmpl': os.path.join(tmpdir, 'video.%(ext)s'),
174
+ 'quiet': True,
175
+ 'noplaylist': True,
176
+ 'merge_output_format': 'mp4',
177
+ 'force_ipv4': True, # Avoid IPv6 issues
178
+ }
179
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
180
+ info = ydl.extract_info(url, download=True)
181
+
182
+ # Find the downloaded file
183
+ video_path = None
184
+ for file in os.listdir(tmpdir):
185
+ if file.endswith('.mp4'):
186
+ video_path = os.path.join(tmpdir, file)
187
+ break
188
+
189
+ if not video_path:
190
+ raise RuntimeError("Failed to download video as mp4")
191
+
192
+ # ✅ Fix: Use `imageio.get_reader()` instead of `imopen()`
193
+ reader = imageio.get_reader(video_path) # Works for frame-by-frame iteration
194
+ metadata = reader.get_meta_data()
195
+ fps = metadata.get('fps')
196
+
197
+ if fps is None:
198
+ reader.close()
199
+ raise RuntimeError("Unable to determine FPS from video metadata")
200
+
201
+ frame_interval = int(fps * sample_interval_seconds)
202
+ images: List[Image.Image] = []
203
+
204
+ # ✅ Iterate over frames using `get_reader()`
205
+ for idx, frame in enumerate(reader):
206
+ if idx % frame_interval == 0:
207
+ images.append(Image.fromarray(frame))
208
+
209
+ reader.close()
210
+ return images
211
+
212
+ @tool
213
+ def read_file(filepath: str ) -> str:
214
+ """
215
+ Used to read the content of a file. Returns the content as a string.
216
+ Will only work for text-based files, such as .txt files or code files.
217
+ Do not use for audio or visual files.
218
+
219
+ Args:
220
+ filepath (str): The path to the file to be read.
221
+
222
+ Returns:
223
+ str: Content of the file as a string.
224
+
225
+ Raises:
226
+ IOError: If there is an error opening or reading from the file.
227
+ """
228
+ try:
229
+ with open(filepath, 'r', encoding='utf-8') as file:
230
+ content = file.read()
231
+ print(content)
232
+ return content
233
+ except FileNotFoundError:
234
+ print(f"File not found: {filepath}")
235
+ except IOError as e:
236
+ print(f"Error reading file: {str(e)}")
237
+
238
+ @tool
239
+ def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
240
+ """
241
+ Download a file from a URL and save it to a temporary location.
242
+ Use this tool when you are asked a question and told that there is a file or image provided.
243
+
244
+
245
+ Args:
246
+ url: The URL to download from
247
+ filename: Optional filename, will generate one based on URL if not provided
248
+
249
+ Returns:
250
+ Path to the downloaded file
251
+ """
252
+ try:
253
+ # Parse URL to get filename if not provided
254
+ print(f"Downloading file from {url}")
255
+ if not filename:
256
+ path = urlparse(url).path
257
+ filename = os.path.basename(path)
258
+ if not filename:
259
+ # Generate a random name if we couldn't extract one
260
+ import uuid
261
+ filename = f"downloaded_{uuid.uuid4().hex[:8]}"
262
+
263
+ # Create temporary file
264
+ temp_dir = tempfile.gettempdir()
265
+ filepath = os.path.join(temp_dir, filename)
266
+
267
+ # Download the file
268
+ response = requests.get(url, stream=True)
269
+ response.raise_for_status()
270
+
271
+ # Save the file
272
+ with open(filepath, 'wb') as f:
273
+ for chunk in response.iter_content(chunk_size=8192):
274
+ f.write(chunk)
275
+
276
+ return f"File downloaded to {filepath}. You can now process this file."
277
+ except Exception as e:
278
+ return f"Error downloading file: {str(e)}"
279
+
280
+ @tool
281
+ def extract_text_from_image(image_path: str) -> str:
282
+ """
283
+ Extract text from an image using pytesseract (if available).
284
+
285
+ Args:
286
+ image_path: Path to the image file
287
+
288
+ Returns:
289
+ Extracted text or error message
290
+ """
291
+ try:
292
+ # Try to import pytesseract
293
+ import pytesseract
294
+ from PIL import Image
295
+
296
+ # Open the image
297
+ image = Image.open(image_path)
298
+
299
+ # Extract text
300
+ text = pytesseract.image_to_string(image)
301
+
302
+ return f"Extracted text from image:\n\n{text}"
303
+ except ImportError:
304
+ return "Error: pytesseract is not installed. Please install it with 'pip install pytesseract' and ensure Tesseract OCR is installed on your system."
305
+ except Exception as e:
306
+ return f"Error extracting text from image: {str(e)}"
307
+
308
+ @tool
309
+ def analyze_csv_file(file_path: str, query: str) -> str:
310
+ """
311
+ Analyze a CSV file using pandas and answer a question about it.
312
+ To use this file you need to have saved it in a location and pass that location to the function.
313
+ The download_file_from_url tool will save it by name to tempfile.gettempdir()
314
+
315
+ Args:
316
+ file_path: Path to the CSV file
317
+ query: Question about the data
318
+
319
+ Returns:
320
+ Analysis result or error message
321
+ """
322
+ try:
323
+ import pandas as pd
324
+
325
+ # Read the CSV file
326
+ df = pd.read_csv(file_path)
327
+
328
+ # Run various analyses based on the query
329
+ result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
330
+ result += f"Columns: {', '.join(df.columns)}\n\n"
331
+
332
+ # Add summary statistics
333
+ result += "Summary statistics:\n"
334
+ result += str(df.describe())
335
+
336
+ return result
337
+ except ImportError:
338
+ return "Error: pandas is not installed. Please install it with 'pip install pandas'."
339
+ except Exception as e:
340
+ return f"Error analyzing CSV file: {str(e)}"
341
+
342
+ @tool
343
+ def analyze_excel_file(file_path: str, query: str) -> str:
344
+ """
345
+ Analyze an Excel file using pandas and answer a question about it.
346
+ To use this file you need to have saved it in a location and pass that location to the function.
347
+ The download_file_from_url tool will save it by name to tempfile.gettempdir()
348
+
349
+ Args:
350
+ file_path: Path to the Excel file
351
+ query: Question about the data
352
+
353
+ Returns:
354
+ Analysis result or error message
355
+ """
356
+ try:
357
+ import pandas as pd
358
+
359
+ # Read the Excel file
360
+ df = pd.read_excel(file_path)
361
+
362
+ # Run various analyses based on the query
363
+ result = f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
364
+ result += f"Columns: {', '.join(df.columns)}\n\n"
365
+
366
+ # Add summary statistics
367
+ result += "Summary statistics:\n"
368
+ result += str(df.describe())
369
+
370
+ return result
371
+ except ImportError:
372
+ return "Error: pandas and openpyxl are not installed. Please install them with 'pip install pandas openpyxl'."
373
+ except Exception as e:
374
+ return f"Error analyzing Excel file: {str(e)}"
375
+
376
+ import whisper
377
+
378
+ @tool
379
+ def youtube_transcribe(url: str) -> str:
380
+ """
381
+ Transcribes a YouTube video. Use when you need to process the audio from a YouTube video into Text.
382
+
383
+ Args:
384
+ url: Url of the YouTube video
385
+ """
386
+ model_size: str = "small"
387
+ # Load model
388
+ model = whisper.load_model(model_size)
389
+ with tempfile.TemporaryDirectory() as tmpdir:
390
+ # Download audio
391
+ ydl_opts = {
392
+ 'format': 'bestaudio/best',
393
+ 'outtmpl': os.path.join(tmpdir, 'audio.%(ext)s'),
394
+ 'quiet': True,
395
+ 'noplaylist': True,
396
+ 'postprocessors': [{
397
+ 'key': 'FFmpegExtractAudio',
398
+ 'preferredcodec': 'wav',
399
+ 'preferredquality': '192',
400
+ }],
401
+ 'force_ipv4': True,
402
+ }
403
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
404
+ info = ydl.extract_info(url, download=True)
405
+
406
+ audio_path = next((os.path.join(tmpdir, f) for f in os.listdir(tmpdir) if f.endswith('.wav')), None)
407
+ if not audio_path:
408
+ raise RuntimeError("Failed to find audio")
409
+
410
+ # Transcribe
411
+ result = model.transcribe(audio_path)
412
+ return result['text']
413
+
414
+ @tool
415
+ def transcribe_audio(audio_file_path: str) -> str:
416
+ """
417
+ Transcribes an audio file. Use when you need to process audio data.
418
+ DO NOT use this tool for YouTube video; use the youtube_transcribe tool to process audio data from YouTube.
419
+ Use this tool when you have an audio file in .mp3, .wav, .aac, .ogg, .flac, .m4a, .alac or .wma
420
+
421
+ Args:
422
+ audio_file_path: Filepath to the audio file (str)
423
+ """
424
+ model_size: str = "small"
425
+ # Load model
426
+ model = whisper.load_model(model_size)
427
+ result = model.transcribe(audio_file_path)
428
+ return result['text']
429
+
430
+ # global driver
431
+ # driver = initialize_driver()