Spaces:
Runtime error
Runtime error
Commit
·
c79086f
0
Parent(s):
score 35
Browse files- .gitattributes +35 -0
- .gitignore +3 -0
- README.md +15 -0
- agents.py +71 -0
- app.py +436 -0
- final_answer.py +71 -0
- managed_agent.ipynb +0 -0
- model_provider.py +17 -0
- prompts.yaml +226 -0
- questions.json +122 -0
- requirements.txt +22 -0
- results.csv +43 -0
- supabase_docs.csv +0 -0
- tools.py +321 -0
.gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
__pycache__/
|
2 |
+
.env
|
3 |
+
cache/
|
README.md
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Template Final Assignment
|
3 |
+
emoji: 🕵🏻♂️
|
4 |
+
colorFrom: indigo
|
5 |
+
colorTo: indigo
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 5.25.2
|
8 |
+
app_file: app.py
|
9 |
+
pinned: false
|
10 |
+
hf_oauth: true
|
11 |
+
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
|
12 |
+
hf_oauth_expiration_minutes: 480
|
13 |
+
---
|
14 |
+
|
15 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
agents.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from smolagents.default_tools import (DuckDuckGoSearchTool,
|
16 |
+
VisitWebpageTool,
|
17 |
+
WikipediaSearchTool,
|
18 |
+
SpeechToTextTool,
|
19 |
+
PythonInterpreterTool)
|
20 |
+
import yaml
|
21 |
+
from final_answer import FinalAnswerTool, check_reasoning, ensure_formatting
|
22 |
+
from tools import (use_vision_model, youtube_frames_to_images,
|
23 |
+
read_file,
|
24 |
+
extract_text_from_image, analyze_csv_file,
|
25 |
+
analyze_excel_file, youtube_transcribe,
|
26 |
+
transcribe_audio, review_youtube_video)
|
27 |
+
import os
|
28 |
+
from model_provider import create_react_model
|
29 |
+
import time
|
30 |
+
|
31 |
+
# Load prompts from YAML file
|
32 |
+
with open("prompts.yaml", 'r') as stream:
|
33 |
+
prompt_templates = yaml.safe_load(stream)
|
34 |
+
|
35 |
+
def get_manager_agent():
|
36 |
+
return CodeAgent(
|
37 |
+
model=create_react_model(),
|
38 |
+
tools=[FinalAnswerTool(),
|
39 |
+
DuckDuckGoSearchTool(),
|
40 |
+
VisitWebpageTool(max_output_length=500000),
|
41 |
+
WikipediaSearchTool(extract_format='HTML'),
|
42 |
+
SpeechToTextTool(),
|
43 |
+
youtube_transcribe,
|
44 |
+
# use_vision_model,
|
45 |
+
# youtube_frames_to_images,
|
46 |
+
# review_youtube_video,
|
47 |
+
read_file,
|
48 |
+
extract_text_from_image,
|
49 |
+
analyze_csv_file, analyze_excel_file,
|
50 |
+
transcribe_audio,
|
51 |
+
],
|
52 |
+
managed_agents=[],
|
53 |
+
additional_authorized_imports=['os', 'pandas', 'numpy', 'PIL', 'tempfile', 'PIL.Image'],
|
54 |
+
max_steps=10,
|
55 |
+
verbosity_level=1,
|
56 |
+
planning_interval=10,
|
57 |
+
name="Manager",
|
58 |
+
description="The manager of the team, responsible for overseeing and guiding the team's work.",
|
59 |
+
final_answer_checks=[
|
60 |
+
check_reasoning,
|
61 |
+
ensure_formatting,
|
62 |
+
],
|
63 |
+
prompt_templates=prompt_templates
|
64 |
+
)
|
65 |
+
|
66 |
+
manager_agent = get_manager_agent()
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
if __name__ == "__main__":
|
71 |
+
GradioUI(manager_agent).launch()
|
app.py
ADDED
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" Basic Agent Evaluation Runner"""
|
2 |
+
import os
|
3 |
+
import gradio as gr
|
4 |
+
import requests
|
5 |
+
import pandas as pd
|
6 |
+
import concurrent.futures
|
7 |
+
import os
|
8 |
+
import gradio as gr
|
9 |
+
import requests
|
10 |
+
import pandas as pd
|
11 |
+
import os
|
12 |
+
from agents import get_manager_agent
|
13 |
+
from typing import Optional
|
14 |
+
|
15 |
+
import os
|
16 |
+
import time
|
17 |
+
import requests
|
18 |
+
from typing import Optional
|
19 |
+
from pathlib import Path
|
20 |
+
|
21 |
+
# File cache to avoid repeated downloads
|
22 |
+
FILE_CACHE_DIR = Path("./cache")
|
23 |
+
FILE_CACHE_DIR.mkdir(exist_ok=True, parents=True)
|
24 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
25 |
+
|
26 |
+
|
27 |
+
class FileCache:
|
28 |
+
"""Handles caching of files to avoid repeated downloads."""
|
29 |
+
|
30 |
+
@staticmethod
|
31 |
+
def get_cached_path(file_name: str) -> Optional[Path]:
|
32 |
+
"""Check if file is already cached."""
|
33 |
+
cache_path = FILE_CACHE_DIR / file_name
|
34 |
+
return cache_path if cache_path.exists() else None
|
35 |
+
|
36 |
+
@staticmethod
|
37 |
+
def cache_file(file_name: str, content: bytes) -> Path:
|
38 |
+
"""Cache file content."""
|
39 |
+
cache_path = FILE_CACHE_DIR / file_name
|
40 |
+
with open(cache_path, 'wb') as f:
|
41 |
+
f.write(content)
|
42 |
+
return cache_path
|
43 |
+
|
44 |
+
@staticmethod
|
45 |
+
def get_file_extension(filename: str) -> str:
|
46 |
+
"""Extract file extension from filename."""
|
47 |
+
return Path(filename).suffix
|
48 |
+
|
49 |
+
class FileManager:
|
50 |
+
"""Handles file retrieval and caching."""
|
51 |
+
|
52 |
+
@staticmethod
|
53 |
+
def get_file_by_task_id(task_id: str, file_name: str) -> Optional[Path]:
|
54 |
+
"""
|
55 |
+
Fetch file associated with task ID and cache it.
|
56 |
+
|
57 |
+
Args:
|
58 |
+
task_id: The ID of the task
|
59 |
+
file_name: The name of the file
|
60 |
+
|
61 |
+
Returns:
|
62 |
+
Path to the cached file, or None if no file exists
|
63 |
+
"""
|
64 |
+
# Check cache first
|
65 |
+
cached_path = FileCache.get_cached_path(file_name)
|
66 |
+
if cached_path:
|
67 |
+
return cached_path
|
68 |
+
|
69 |
+
# If not cached, download
|
70 |
+
url = f"{DEFAULT_API_URL}/files/{task_id}"
|
71 |
+
try:
|
72 |
+
response = requests.get(url, timeout=10)
|
73 |
+
response.raise_for_status()
|
74 |
+
|
75 |
+
# Cache the file
|
76 |
+
content = response.content
|
77 |
+
cached_path = FileCache.cache_file(file_name, content)
|
78 |
+
|
79 |
+
return cached_path
|
80 |
+
except Exception as e:
|
81 |
+
print(f"Error fetching file for task {task_id}: {e}")
|
82 |
+
return None
|
83 |
+
|
84 |
+
|
85 |
+
# (Keep Constants as is)
|
86 |
+
# --- Constants ---
|
87 |
+
|
88 |
+
class BasicAgent:
|
89 |
+
def __init__(self):
|
90 |
+
print("BasicAgent initialized.")
|
91 |
+
self.agent = get_manager_agent()
|
92 |
+
self.verbose = True
|
93 |
+
|
94 |
+
def __call__(self, task_id: str, question: str, file_name: str = None) -> str:
|
95 |
+
"""
|
96 |
+
Process a GAIA benchmark question and return the answer
|
97 |
+
|
98 |
+
Args:
|
99 |
+
question: The question to answer
|
100 |
+
task_file_path: Optional path to a file associated with the question
|
101 |
+
|
102 |
+
Returns:
|
103 |
+
The answer to the question
|
104 |
+
"""
|
105 |
+
|
106 |
+
task_file_path = None
|
107 |
+
if file_name:
|
108 |
+
task_file_path = FileManager.get_file_by_task_id(task_id, file_name)
|
109 |
+
|
110 |
+
try:
|
111 |
+
if self.verbose:
|
112 |
+
print(f"Processing question: {question}")
|
113 |
+
if task_file_path:
|
114 |
+
print(f"With associated file: {task_file_path}")
|
115 |
+
|
116 |
+
# Create a context with file information if available
|
117 |
+
context = question
|
118 |
+
|
119 |
+
# If there's a file, read it and include its content in the context
|
120 |
+
if task_file_path:
|
121 |
+
context = f"""
|
122 |
+
Question: {question}
|
123 |
+
|
124 |
+
This question has an associated file. File is already downloaded at:
|
125 |
+
{task_file_path}
|
126 |
+
|
127 |
+
Analyze the file content above to answer the question using tools.
|
128 |
+
"""
|
129 |
+
|
130 |
+
# Check for special cases that need specific formatting
|
131 |
+
# Reversed text questions
|
132 |
+
if question.startswith(".") or ".rewsna eht sa" in question:
|
133 |
+
context = f"""
|
134 |
+
This question appears to be in reversed text. Here's the reversed version:
|
135 |
+
{question[::-1]}
|
136 |
+
|
137 |
+
Now answer the question above. Remember to format your answer exactly as requested.
|
138 |
+
"""
|
139 |
+
|
140 |
+
# Add a prompt to ensure precise answers
|
141 |
+
full_prompt = f"""{context}
|
142 |
+
|
143 |
+
When answering, provide ONLY the precise answer requested.
|
144 |
+
Do not include explanations, steps, reasoning, or additional text.
|
145 |
+
Be direct and specific. GAIA benchmark requires exact matching answers.
|
146 |
+
For example, if asked "What is the capital of France?", respond simply with "Paris".
|
147 |
+
"""
|
148 |
+
|
149 |
+
# Run the agent with the question
|
150 |
+
answer = self.agent.run(full_prompt)
|
151 |
+
|
152 |
+
# Clean up the answer to ensure it's in the expected format
|
153 |
+
# Remove common prefixes that models often add
|
154 |
+
answer = self._clean_answer(answer)
|
155 |
+
|
156 |
+
if self.verbose:
|
157 |
+
print(f"Generated answer: {answer}")
|
158 |
+
|
159 |
+
return answer
|
160 |
+
except Exception as e:
|
161 |
+
error_msg = f"Error answering question: {e}"
|
162 |
+
if self.verbose:
|
163 |
+
print(error_msg)
|
164 |
+
return error_msg
|
165 |
+
|
166 |
+
def _clean_answer(self, answer: any) -> str:
|
167 |
+
"""
|
168 |
+
Clean up the answer to remove common prefixes and formatting
|
169 |
+
that models often add but that can cause exact match failures.
|
170 |
+
|
171 |
+
Args:
|
172 |
+
answer: The raw answer from the model
|
173 |
+
|
174 |
+
Returns:
|
175 |
+
The cleaned answer as a string
|
176 |
+
"""
|
177 |
+
# Convert non-string types to strings
|
178 |
+
if not isinstance(answer, str):
|
179 |
+
# Handle numeric types (float, int)
|
180 |
+
if isinstance(answer, float):
|
181 |
+
# Format floating point numbers properly
|
182 |
+
# Check if it's an integer value in float form (e.g., 12.0)
|
183 |
+
if answer.is_integer():
|
184 |
+
formatted_answer = str(int(answer))
|
185 |
+
else:
|
186 |
+
# For currency values that might need formatting
|
187 |
+
if abs(answer) >= 1000:
|
188 |
+
formatted_answer = f"${answer:,.2f}"
|
189 |
+
else:
|
190 |
+
formatted_answer = str(answer)
|
191 |
+
return formatted_answer
|
192 |
+
elif isinstance(answer, int):
|
193 |
+
return str(answer)
|
194 |
+
else:
|
195 |
+
# For any other type
|
196 |
+
return str(answer)
|
197 |
+
|
198 |
+
# Now we know answer is a string, so we can safely use string methods
|
199 |
+
# Normalize whitespace
|
200 |
+
answer = answer.strip()
|
201 |
+
|
202 |
+
# Remove common prefixes and formatting that models add
|
203 |
+
prefixes_to_remove = [
|
204 |
+
"The answer is ",
|
205 |
+
"Answer: ",
|
206 |
+
"Final answer: ",
|
207 |
+
"The result is ",
|
208 |
+
"To answer this question: ",
|
209 |
+
"Based on the information provided, ",
|
210 |
+
"According to the information: ",
|
211 |
+
]
|
212 |
+
|
213 |
+
for prefix in prefixes_to_remove:
|
214 |
+
if answer.startswith(prefix):
|
215 |
+
answer = answer[len(prefix):].strip()
|
216 |
+
|
217 |
+
# Remove quotes if they wrap the entire answer
|
218 |
+
if (answer.startswith('"') and answer.endswith('"')) or (answer.startswith("'") and answer.endswith("'")):
|
219 |
+
answer = answer[1:-1].strip()
|
220 |
+
|
221 |
+
return answer
|
222 |
+
|
223 |
+
|
224 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
225 |
+
"""
|
226 |
+
Fetches all questions, runs the BasicAgent on them in parallel (up to 10 at a time),
|
227 |
+
submits all answers, and displays the results.
|
228 |
+
"""
|
229 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
230 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
231 |
+
|
232 |
+
if profile:
|
233 |
+
username= f"{profile.username}"
|
234 |
+
print(f"User logged in: {username}")
|
235 |
+
else:
|
236 |
+
print("User not logged in.")
|
237 |
+
return "Please Login to Hugging Face with the button.", None
|
238 |
+
|
239 |
+
api_url = DEFAULT_API_URL
|
240 |
+
questions_url = f"{api_url}/questions"
|
241 |
+
submit_url = f"{api_url}/submit"
|
242 |
+
|
243 |
+
# 1. Instantiate Agent (modify this part to create your agent)
|
244 |
+
try:
|
245 |
+
agent = BasicAgent()
|
246 |
+
except Exception as e:
|
247 |
+
print(f"Error instantiating agent: {e}")
|
248 |
+
return f"Error initializing agent: {e}", None
|
249 |
+
|
250 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase
|
251 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
252 |
+
print(agent_code)
|
253 |
+
|
254 |
+
# 2. Fetch Questions
|
255 |
+
print(f"Fetching questions from: {questions_url}")
|
256 |
+
try:
|
257 |
+
response = requests.get(questions_url, timeout=15)
|
258 |
+
response.raise_for_status()
|
259 |
+
questions_data = response.json()
|
260 |
+
if not questions_data:
|
261 |
+
print("Fetched questions list is empty.")
|
262 |
+
return "Fetched questions list is empty or invalid format.", None
|
263 |
+
print(f"Fetched {len(questions_data)} questions.")
|
264 |
+
except requests.exceptions.RequestException as e:
|
265 |
+
print(f"Error fetching questions: {e}")
|
266 |
+
return f"Error fetching questions: {e}", None
|
267 |
+
except requests.exceptions.JSONDecodeError as e:
|
268 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
269 |
+
print(f"Response text: {response.text[:500]}")
|
270 |
+
return f"Error decoding server response for questions: {e}", None
|
271 |
+
except Exception as e:
|
272 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
273 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
274 |
+
|
275 |
+
# Helper function to process a single question
|
276 |
+
def process_question(item):
|
277 |
+
task_id = item.get("task_id")
|
278 |
+
question_text = item.get("question")
|
279 |
+
file_name = item.get("file_name")
|
280 |
+
|
281 |
+
if not task_id or question_text is None:
|
282 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
283 |
+
return None
|
284 |
+
|
285 |
+
try:
|
286 |
+
submitted_answer = BasicAgent()(task_id, question_text, file_name)
|
287 |
+
return {
|
288 |
+
"task_id": task_id,
|
289 |
+
"question": question_text,
|
290 |
+
"submitted_answer": submitted_answer,
|
291 |
+
"error": None
|
292 |
+
}
|
293 |
+
except Exception as e:
|
294 |
+
# raise e
|
295 |
+
print(f"Error running agent on task {task_id}: {e}")
|
296 |
+
return {
|
297 |
+
"task_id": task_id,
|
298 |
+
"question": question_text,
|
299 |
+
"submitted_answer": f"AGENT ERROR: {e}",
|
300 |
+
"error": str(e)
|
301 |
+
}
|
302 |
+
|
303 |
+
# 3. Run your Agent in parallel (up to 10 at a time)
|
304 |
+
results_log = []
|
305 |
+
answers_payload = []
|
306 |
+
print(f"Running agent on {len(questions_data)} questions with up to 10 in parallel...")
|
307 |
+
|
308 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=19) as executor:
|
309 |
+
# Submit all questions to the thread pool
|
310 |
+
future_to_item = {
|
311 |
+
executor.submit(process_question, item): item
|
312 |
+
for item in questions_data
|
313 |
+
}
|
314 |
+
|
315 |
+
# Collect results as they complete
|
316 |
+
for future in concurrent.futures.as_completed(future_to_item):
|
317 |
+
result = future.result()
|
318 |
+
if result is not None:
|
319 |
+
if result["error"] is None:
|
320 |
+
answers_payload.append({
|
321 |
+
"task_id": result["task_id"],
|
322 |
+
"submitted_answer": result["submitted_answer"]
|
323 |
+
})
|
324 |
+
results_log.append({
|
325 |
+
"Task ID": result["task_id"],
|
326 |
+
"Question": result["question"],
|
327 |
+
"Submitted Answer": result["submitted_answer"]
|
328 |
+
})
|
329 |
+
|
330 |
+
if not answers_payload:
|
331 |
+
print("Agent did not produce any answers to submit.")
|
332 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
333 |
+
|
334 |
+
# 4. Prepare Submission
|
335 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
336 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
337 |
+
print(status_update)
|
338 |
+
|
339 |
+
# 5. Submit
|
340 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
341 |
+
try:
|
342 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
343 |
+
response.raise_for_status()
|
344 |
+
result_data = response.json()
|
345 |
+
final_status = (
|
346 |
+
f"Submission Successful!\n"
|
347 |
+
f"User: {result_data.get('username')}\n"
|
348 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
349 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
350 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
351 |
+
)
|
352 |
+
print("Submission successful.")
|
353 |
+
results_df = pd.DataFrame(results_log)
|
354 |
+
# save to csv
|
355 |
+
results_df.to_csv("results.csv", index=False)
|
356 |
+
return final_status, results_df
|
357 |
+
except requests.exceptions.HTTPError as e:
|
358 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
359 |
+
try:
|
360 |
+
error_json = e.response.json()
|
361 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
362 |
+
except requests.exceptions.JSONDecodeError:
|
363 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
364 |
+
status_message = f"Submission Failed: {error_detail}"
|
365 |
+
print(status_message)
|
366 |
+
results_df = pd.DataFrame(results_log)
|
367 |
+
return status_message, results_df
|
368 |
+
except requests.exceptions.Timeout:
|
369 |
+
status_message = "Submission Failed: The request timed out."
|
370 |
+
print(status_message)
|
371 |
+
results_df = pd.DataFrame(results_log)
|
372 |
+
return status_message, results_df
|
373 |
+
except requests.exceptions.RequestException as e:
|
374 |
+
status_message = f"Submission Failed: Network error - {e}"
|
375 |
+
print(status_message)
|
376 |
+
results_df = pd.DataFrame(results_log)
|
377 |
+
return status_message, results_df
|
378 |
+
except Exception as e:
|
379 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
380 |
+
print(status_message)
|
381 |
+
results_df = pd.DataFrame(results_log)
|
382 |
+
return status_message, results_df
|
383 |
+
|
384 |
+
|
385 |
+
# --- Build Gradio Interface using Blocks ---
|
386 |
+
with gr.Blocks() as demo:
|
387 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
388 |
+
gr.Markdown(
|
389 |
+
"""
|
390 |
+
**Instructions:**
|
391 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
392 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
393 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
394 |
+
---
|
395 |
+
**Disclaimers:**
|
396 |
+
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).
|
397 |
+
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
398 |
+
"""
|
399 |
+
)
|
400 |
+
|
401 |
+
gr.LoginButton()
|
402 |
+
|
403 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
404 |
+
|
405 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
406 |
+
# Removed max_rows=10 from DataFrame constructor
|
407 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
408 |
+
|
409 |
+
run_button.click(
|
410 |
+
fn=run_and_submit_all,
|
411 |
+
outputs=[status_output, results_table]
|
412 |
+
)
|
413 |
+
|
414 |
+
if __name__ == "__main__":
|
415 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
416 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
417 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
418 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
419 |
+
|
420 |
+
if space_host_startup:
|
421 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
422 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
423 |
+
else:
|
424 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
425 |
+
|
426 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
427 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
428 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
429 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
430 |
+
else:
|
431 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
432 |
+
|
433 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
434 |
+
|
435 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
436 |
+
demo.launch(debug=True, share=False)
|
final_answer.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any
|
2 |
+
from smolagents.tools import Tool
|
3 |
+
from model_provider import create_react_model
|
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 |
+
prompt = f"""
|
20 |
+
Here is a user-given task and the agent steps: {agent_memory.get_succinct_steps()}. Now here is the answer that was given:
|
21 |
+
{final_answer}
|
22 |
+
Please check that the reasoning process and results are correct: do they correctly answer the given task?
|
23 |
+
First list reasons why yes/no, then write your final decision: PASS in caps lock if it is satisfactory, FAIL if it is not.
|
24 |
+
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.
|
25 |
+
"""
|
26 |
+
messages = [
|
27 |
+
{
|
28 |
+
"role": "user",
|
29 |
+
"content": [
|
30 |
+
{
|
31 |
+
"type": "text",
|
32 |
+
"text": prompt,
|
33 |
+
}
|
34 |
+
]
|
35 |
+
}
|
36 |
+
]
|
37 |
+
output = create_react_model()(messages).content
|
38 |
+
print("Feedback: ", output)
|
39 |
+
if "FAIL" in output:
|
40 |
+
raise Exception(output)
|
41 |
+
return True
|
42 |
+
|
43 |
+
def ensure_formatting(final_answer, agent_memory):
|
44 |
+
prompt = f"""
|
45 |
+
Here is a user-given task and the agent steps: {agent_memory.get_succinct_steps()}. Now here is the FINAL ANSWER that was given:
|
46 |
+
{final_answer}
|
47 |
+
Ensure the FINAL ANSWER is in the right format as asked for by the task. Here are the instructions that you need to evaluate:
|
48 |
+
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
49 |
+
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.
|
50 |
+
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
|
51 |
+
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.
|
52 |
+
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.
|
53 |
+
If you are asked for a comma separated list, ensure you only return the content of that list, and NOT the brackets '[]'
|
54 |
+
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.
|
55 |
+
"""
|
56 |
+
messages = [
|
57 |
+
{
|
58 |
+
"role": "user",
|
59 |
+
"content": [
|
60 |
+
{
|
61 |
+
"type": "text",
|
62 |
+
"text": prompt,
|
63 |
+
}
|
64 |
+
]
|
65 |
+
}
|
66 |
+
]
|
67 |
+
output = create_react_model()(messages).content
|
68 |
+
print("Feedback: ", output)
|
69 |
+
if "FAIL" in output:
|
70 |
+
raise Exception(output)
|
71 |
+
return True
|
managed_agent.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
model_provider.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from smolagents import (OpenAIServerModel)
|
3 |
+
from dotenv import load_dotenv
|
4 |
+
load_dotenv(override=True)
|
5 |
+
|
6 |
+
OPENAI_MODEL = os.getenv("OPENAI_MODEL")
|
7 |
+
OPENAI_BASE = os.getenv("OPENAI_API_BASE")
|
8 |
+
OPENAI_KEY = os.getenv("OPENAI_API_KEY")
|
9 |
+
|
10 |
+
|
11 |
+
def create_react_model():
|
12 |
+
return OpenAIServerModel(model_id=OPENAI_MODEL, api_base=OPENAI_BASE, api_key=OPENAI_KEY)
|
13 |
+
|
14 |
+
def create_vision_model():
|
15 |
+
return OpenAIServerModel(model_id=OPENAI_MODEL, api_base=OPENAI_BASE, api_key=OPENAI_KEY)
|
16 |
+
|
17 |
+
react_model = create_react_model()
|
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 '[]'
|
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
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
python==3.12.6
|
2 |
+
smolagents[transformers]>=1.14.0
|
3 |
+
pytz>=2025.2
|
4 |
+
gradio>=5.26.0
|
5 |
+
litellm>=1.67.2
|
6 |
+
gradiologin>=0.1.0
|
7 |
+
helium>=5.1.1
|
8 |
+
selenium>=4.31.0
|
9 |
+
imageio[ffmpeg]>=2.37.0
|
10 |
+
pytesseract>=0.3.13
|
11 |
+
duckduckgo-search>=8.0.1
|
12 |
+
markdownify>=1.1.0
|
13 |
+
pytube>=15.0.0
|
14 |
+
pillow>=11.2.1
|
15 |
+
yt-dlp>=2025.3.31
|
16 |
+
wikipedia-api>=0.8.1
|
17 |
+
transformers>=4.51.3
|
18 |
+
openai-whisper>=20240930
|
19 |
+
pandas>=2.2.3
|
20 |
+
openpyxl>=3.1.5
|
21 |
+
google-genai>=1.12.1
|
22 |
+
ipywidgets>=8.1.6
|
results.csv
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Task ID,Question,Submitted Answer
|
2 |
+
2d83110e-a098-4ebb-9987-066c06fa42d0,".rewsna eht sa ""tfel"" drow eht fo etisoppo eht etirw ,ecnetnes siht dnatsrednu uoy fI",right
|
3 |
+
9d191bce-651d-4746-be2d-7ef8ecadb9c2,"Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.
|
4 |
+
|
5 |
+
What does Teal'c say in response to the question ""Isn't that hot?""",Extremely
|
6 |
+
99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3,"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.
|
7 |
+
|
8 |
+
In 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"".
|
9 |
+
|
10 |
+
Please format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.","salt, sugar, strawberries"
|
11 |
+
bda648d7-d618-4883-88f4-3466eabd860e,Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations.,St. Petersburg
|
12 |
+
8e867cd7-cff9-4e6c-867a-ff5ddc2550be,How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.,4
|
13 |
+
4fc2f1ae-8625-45b5-ab34-ad4433bc21f8,Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?,Ian Rose
|
14 |
+
305ac316-eef6-4446-960a-92d80d542f82,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.,Wojtek
|
15 |
+
840bfca7-4f7b-481a-8794-c560c340185d,"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?",80GSFC21M0002
|
16 |
+
7bd855d8-463d-4ed5-93ca-5fe35145f733,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.,$89705.97
|
17 |
+
cf106601-ab4f-4af9-b045-5295fe67b37d,"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.",LUX
|
18 |
+
3f57289b-8c60-48be-bd80-01f8099ca449,How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?,519
|
19 |
+
cabe07ed-9eca-40ea-8ead-410ef5e83f91,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?,The specified materials do not mention an equine veterinarian.
|
20 |
+
3cef3a44-215e-4aed-8e3b-b1e3f08063b7,"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:
|
21 |
+
|
22 |
+
milk, 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
|
23 |
+
|
24 |
+
I 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.","broccoli, celery, corn, green beans, lettuce, peanuts, sweet potatoes"
|
25 |
+
1f975693-876d-457b-a649-393859e79bf3,"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 :(
|
26 |
+
|
27 |
+
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.","132,133,134,197,245"
|
28 |
+
a0c07678-e491-4bbc-8f0b-07405144218f,"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.","Morishita, Kuribayashi"
|
29 |
+
5a0c1adf-205e-4841-a666-7c3ef95def9d,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?,Claus
|
30 |
+
f918266a-b3e0-4914-865d-4faa564f1aef,What is the final numeric output from the attached Python code?,0
|
31 |
+
a1e91b78-d3d8-4675-bb8d-62741b4b68a6,"In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?",3
|
32 |
+
6f37996b-2ac7-44b0-8e68-6d28256631b4,"Given this table defining * on the set S = {a, b, c, d, e}
|
33 |
+
|
34 |
+
|*|a|b|c|d|e|
|
35 |
+
|---|---|---|---|---|---|
|
36 |
+
|a|a|b|c|b|d|
|
37 |
+
|b|b|c|a|e|c|
|
38 |
+
|c|c|a|b|b|a|
|
39 |
+
|d|b|e|b|e|d|
|
40 |
+
|e|d|b|a|d|c|
|
41 |
+
|
42 |
+
provide 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.","b,c,d,e"
|
43 |
+
cca530fc-4052-43b2-b130-b30968d8aa44,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.,Error: Unable to analyze chess position. Image processing tools are unavailable.
|
supabase_docs.csv
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tools.py
ADDED
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from google.genai import types
|
10 |
+
|
11 |
+
from PIL import Image
|
12 |
+
from smolagents import CodeAgent, tool, OpenAIServerModel, LiteLLMModel
|
13 |
+
from google import genai
|
14 |
+
from dotenv import load_dotenv
|
15 |
+
from model_provider import create_react_model, create_vision_model
|
16 |
+
import imageio
|
17 |
+
|
18 |
+
load_dotenv(override=True)
|
19 |
+
|
20 |
+
@tool
|
21 |
+
def use_vision_model(question: str, images: List[Image.Image]) -> str:
|
22 |
+
"""
|
23 |
+
Use a Vision Model to answer a question about a set of images.
|
24 |
+
Always use this tool to ask questions about a set of images you have been provided.
|
25 |
+
This function uses an image-to-text AI model.
|
26 |
+
You can ask a question about a list of one image or a list of multiple images.
|
27 |
+
So, if you have multiple images that you want to ask the same question of, pass the entire list of images to the model.
|
28 |
+
Ensure your prompt is specific enough to retrieve the exact information you are looking for.
|
29 |
+
|
30 |
+
Args:
|
31 |
+
question: The question to ask about the images. Type: str
|
32 |
+
images: The list of images to as the question about. Type: List[PIL.Image.Image]
|
33 |
+
"""
|
34 |
+
image_model = create_vision_model()
|
35 |
+
|
36 |
+
content = [
|
37 |
+
{
|
38 |
+
"type": "text",
|
39 |
+
"text": question
|
40 |
+
}
|
41 |
+
]
|
42 |
+
print(f"Asking model a question about {len(images)} images")
|
43 |
+
for image in images:
|
44 |
+
content.append({
|
45 |
+
"type": "image",
|
46 |
+
"image": image # ✅ Directly the PIL Image, no wrapping
|
47 |
+
})
|
48 |
+
|
49 |
+
messages = [
|
50 |
+
{
|
51 |
+
"role": "user",
|
52 |
+
"content": content
|
53 |
+
}
|
54 |
+
]
|
55 |
+
|
56 |
+
output = image_model(messages).content
|
57 |
+
print(f'Model returned: {output}')
|
58 |
+
return output
|
59 |
+
|
60 |
+
@tool
|
61 |
+
def youtube_frames_to_images(url: str, sample_interval_frames: int = 24) -> List[Image.Image]:
|
62 |
+
"""
|
63 |
+
Reviews a YouTube video and returns a List of PIL Images (List[PIL.Image.Image]), which can then be reviewed by a vision model.
|
64 |
+
Only use this tool if you have been given a YouTube video that you need to analyze.
|
65 |
+
This will generate a list of images, and you can use the use_vision_model tool to analyze those images
|
66 |
+
Args:
|
67 |
+
url: The Youtube URL
|
68 |
+
sample_interval_frames: The sampling interval (default is 24 frames)
|
69 |
+
"""
|
70 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
71 |
+
# Download the video locally
|
72 |
+
ydl_opts = {
|
73 |
+
'format': 'bestvideo[height<=1080]+bestaudio/best[height<=1080]/best',
|
74 |
+
'outtmpl': os.path.join(tmpdir, 'video.%(ext)s'),
|
75 |
+
'quiet': True,
|
76 |
+
'noplaylist': True,
|
77 |
+
'merge_output_format': 'mp4',
|
78 |
+
'force_ipv4': True, # Avoid IPv6 issues
|
79 |
+
}
|
80 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
81 |
+
info = ydl.extract_info(url, download=True)
|
82 |
+
|
83 |
+
# Find the downloaded file
|
84 |
+
video_path = None
|
85 |
+
for file in os.listdir(tmpdir):
|
86 |
+
if file.endswith('.mp4'):
|
87 |
+
video_path = os.path.join(tmpdir, file)
|
88 |
+
break
|
89 |
+
|
90 |
+
if not video_path:
|
91 |
+
raise RuntimeError("Failed to download video as mp4")
|
92 |
+
|
93 |
+
# ✅ Fix: Use `imageio.get_reader()` instead of `imopen()`
|
94 |
+
reader = imageio.get_reader(video_path) # Works for frame-by-frame iteration
|
95 |
+
# metadata = reader.get_meta_data()
|
96 |
+
# fps = metadata.get('fps')
|
97 |
+
|
98 |
+
# if fps is None:
|
99 |
+
# reader.close()
|
100 |
+
# raise RuntimeError("Unable to determine FPS from video metadata")
|
101 |
+
|
102 |
+
# frame_interval = int(fps * sample_interval_frames)
|
103 |
+
frame_interval = sample_interval_frames # Use the provided interval directly
|
104 |
+
images: List[Image.Image] = []
|
105 |
+
|
106 |
+
# ✅ Iterate over frames using `get_reader()`
|
107 |
+
for idx, frame in enumerate(reader):
|
108 |
+
print(f"Processing frame {idx}")
|
109 |
+
if idx % frame_interval == 0:
|
110 |
+
images.append(Image.fromarray(frame))
|
111 |
+
|
112 |
+
reader.close()
|
113 |
+
return images
|
114 |
+
|
115 |
+
@tool
|
116 |
+
def review_youtube_video(url: str, question: str) -> str:
|
117 |
+
"""
|
118 |
+
Reviews a YouTube video and answers a specific question about that video.
|
119 |
+
|
120 |
+
Args:
|
121 |
+
url (str): the URL to the YouTube video. Should be like this format: https://www.youtube.com/watch?v=9hE5-98ZeCg
|
122 |
+
question (str): The question you are asking about the video
|
123 |
+
"""
|
124 |
+
try:
|
125 |
+
client = genai.Client(api_key=os.getenv('GEMINI_KEY'))
|
126 |
+
model = 'gemini-2.0-flash-lite'
|
127 |
+
response = client.models.generate_content(
|
128 |
+
model=model,
|
129 |
+
contents=types.Content(
|
130 |
+
parts=[
|
131 |
+
types.Part(
|
132 |
+
file_data=types.FileData(file_uri=url)
|
133 |
+
),
|
134 |
+
types.Part(text=question)
|
135 |
+
]
|
136 |
+
)
|
137 |
+
)
|
138 |
+
return response.text
|
139 |
+
except Exception as e:
|
140 |
+
return f"Error asking {model} about video: {str(e)}"
|
141 |
+
|
142 |
+
|
143 |
+
@tool
|
144 |
+
def read_file(filepath: str ) -> str:
|
145 |
+
"""
|
146 |
+
Used to read the content of a file. Returns the content as a string.
|
147 |
+
Will only work for text-based files, such as .txt files or code files.
|
148 |
+
Do not use for audio or visual files.
|
149 |
+
|
150 |
+
Args:
|
151 |
+
filepath (str): The path to the file to be read.
|
152 |
+
|
153 |
+
Returns:
|
154 |
+
str: Content of the file as a string.
|
155 |
+
|
156 |
+
Raises:
|
157 |
+
IOError: If there is an error opening or reading from the file.
|
158 |
+
"""
|
159 |
+
try:
|
160 |
+
with open(filepath, 'r', encoding='utf-8') as file:
|
161 |
+
content = file.read()
|
162 |
+
print(content)
|
163 |
+
return content
|
164 |
+
except FileNotFoundError:
|
165 |
+
print(f"File not found: {filepath}")
|
166 |
+
except IOError as e:
|
167 |
+
print(f"Error reading file: {str(e)}")
|
168 |
+
|
169 |
+
|
170 |
+
@tool
|
171 |
+
def extract_text_from_image(image_path: str) -> str:
|
172 |
+
"""
|
173 |
+
Extract text from an image using pytesseract (if available).
|
174 |
+
|
175 |
+
Args:
|
176 |
+
image_path: Path to the image file
|
177 |
+
|
178 |
+
Returns:
|
179 |
+
Extracted text or error message
|
180 |
+
"""
|
181 |
+
try:
|
182 |
+
# Try to import pytesseract
|
183 |
+
import pytesseract
|
184 |
+
from PIL import Image
|
185 |
+
|
186 |
+
# Open the image
|
187 |
+
image = Image.open(image_path)
|
188 |
+
|
189 |
+
# Extract text
|
190 |
+
text = pytesseract.image_to_string(image)
|
191 |
+
|
192 |
+
return f"Extracted text from image:\n\n{text}"
|
193 |
+
except ImportError:
|
194 |
+
return "Error: pytesseract is not installed. Please install it with 'pip install pytesseract' and ensure Tesseract OCR is installed on your system."
|
195 |
+
except Exception as e:
|
196 |
+
return f"Error extracting text from image: {str(e)}"
|
197 |
+
|
198 |
+
@tool
|
199 |
+
def analyze_csv_file(file_path: str, query: str) -> str:
|
200 |
+
"""
|
201 |
+
Analyze a CSV file using pandas and answer a question about it.
|
202 |
+
To use this file you need to have saved it in a location and pass that location to the function.
|
203 |
+
The download_file_from_url tool will save it by name to tempfile.gettempdir()
|
204 |
+
|
205 |
+
Args:
|
206 |
+
file_path: Path to the CSV file
|
207 |
+
query: Question about the data
|
208 |
+
|
209 |
+
Returns:
|
210 |
+
Analysis result or error message
|
211 |
+
"""
|
212 |
+
try:
|
213 |
+
import pandas as pd
|
214 |
+
|
215 |
+
# Read the CSV file
|
216 |
+
df = pd.read_csv(file_path)
|
217 |
+
|
218 |
+
# Run various analyses based on the query
|
219 |
+
result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
220 |
+
result += f"Columns: {', '.join(df.columns)}\n\n"
|
221 |
+
|
222 |
+
# Add summary statistics
|
223 |
+
result += "Summary statistics:\n"
|
224 |
+
result += str(df.describe())
|
225 |
+
|
226 |
+
return result
|
227 |
+
except ImportError:
|
228 |
+
return "Error: pandas is not installed. Please install it with 'pip install pandas'."
|
229 |
+
except Exception as e:
|
230 |
+
return f"Error analyzing CSV file: {str(e)}"
|
231 |
+
|
232 |
+
@tool
|
233 |
+
def analyze_excel_file(file_path: str, query: str) -> str:
|
234 |
+
"""
|
235 |
+
Analyze an Excel file using pandas and answer a question about it.
|
236 |
+
To use this file you need to have saved it in a location and pass that location to the function.
|
237 |
+
The download_file_from_url tool will save it by name to tempfile.gettempdir()
|
238 |
+
|
239 |
+
Args:
|
240 |
+
file_path: Path to the Excel file
|
241 |
+
query: Question about the data
|
242 |
+
|
243 |
+
Returns:
|
244 |
+
Analysis result or error message
|
245 |
+
"""
|
246 |
+
try:
|
247 |
+
import pandas as pd
|
248 |
+
|
249 |
+
# Read the Excel file
|
250 |
+
df = pd.read_excel(file_path)
|
251 |
+
|
252 |
+
# Run various analyses based on the query
|
253 |
+
result = f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
254 |
+
result += f"Columns: {', '.join(df.columns)}\n\n"
|
255 |
+
|
256 |
+
# Add summary statistics
|
257 |
+
result += "Summary statistics:\n"
|
258 |
+
result += str(df.describe())
|
259 |
+
|
260 |
+
return result
|
261 |
+
except ImportError:
|
262 |
+
return "Error: pandas and openpyxl are not installed. Please install them with 'pip install pandas openpyxl'."
|
263 |
+
except Exception as e:
|
264 |
+
return f"Error analyzing Excel file: {str(e)}"
|
265 |
+
|
266 |
+
import whisper
|
267 |
+
|
268 |
+
@tool
|
269 |
+
def youtube_transcribe(url: str) -> str:
|
270 |
+
"""
|
271 |
+
Transcribes a YouTube video. Use when you need to process the audio from a YouTube video into Text.
|
272 |
+
|
273 |
+
Args:
|
274 |
+
url: Url of the YouTube video
|
275 |
+
"""
|
276 |
+
model_size: str = "base"
|
277 |
+
# Load model
|
278 |
+
model = whisper.load_model(model_size)
|
279 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
280 |
+
# Download audio
|
281 |
+
ydl_opts = {
|
282 |
+
'format': 'bestaudio/best',
|
283 |
+
'outtmpl': os.path.join(tmpdir, 'audio.%(ext)s'),
|
284 |
+
'quiet': True,
|
285 |
+
'noplaylist': True,
|
286 |
+
'postprocessors': [{
|
287 |
+
'key': 'FFmpegExtractAudio',
|
288 |
+
'preferredcodec': 'wav',
|
289 |
+
'preferredquality': '192',
|
290 |
+
}],
|
291 |
+
'force_ipv4': True,
|
292 |
+
}
|
293 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
294 |
+
info = ydl.extract_info(url, download=True)
|
295 |
+
|
296 |
+
audio_path = next((os.path.join(tmpdir, f) for f in os.listdir(tmpdir) if f.endswith('.wav')), None)
|
297 |
+
if not audio_path:
|
298 |
+
raise RuntimeError("Failed to find audio")
|
299 |
+
|
300 |
+
# Transcribe
|
301 |
+
result = model.transcribe(audio_path)
|
302 |
+
return result['text']
|
303 |
+
|
304 |
+
@tool
|
305 |
+
def transcribe_audio(audio_file_path: str) -> str:
|
306 |
+
"""
|
307 |
+
Transcribes an audio file. Use when you need to process audio data.
|
308 |
+
DO NOT use this tool for YouTube video; use the youtube_transcribe tool to process audio data from YouTube.
|
309 |
+
Use this tool when you have an audio file in .mp3, .wav, .aac, .ogg, .flac, .m4a, .alac or .wma
|
310 |
+
|
311 |
+
Args:
|
312 |
+
audio_file_path: Filepath to the audio file (str)
|
313 |
+
"""
|
314 |
+
model_size: str = "small"
|
315 |
+
# Load model
|
316 |
+
model = whisper.load_model(model_size)
|
317 |
+
result = model.transcribe(audio_file_path)
|
318 |
+
return result['text']
|
319 |
+
|
320 |
+
# global driver
|
321 |
+
# driver = initialize_driver()
|