Created new files to specify tools, models, and agents
Browse files
agent.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
from smolagents import (
|
| 2 |
CodeAgent,
|
| 3 |
PythonInterpreterTool,
|
|
@@ -6,90 +8,187 @@ from smolagents import (
|
|
| 6 |
)
|
| 7 |
from models import select_model
|
| 8 |
|
| 9 |
-
from
|
| 10 |
-
save_and_read_file,
|
| 11 |
-
analyze_excel_file,
|
| 12 |
-
analyze_csv_file,
|
| 13 |
-
download_file_from_url,
|
| 14 |
-
multiply,
|
| 15 |
-
add,
|
| 16 |
-
subtract,
|
| 17 |
-
divide,
|
| 18 |
-
modulus,
|
| 19 |
-
)
|
| 20 |
|
| 21 |
-
|
| 22 |
-
"pandas",
|
| 23 |
-
"numpy",
|
| 24 |
-
"datetime",
|
| 25 |
-
"json",
|
| 26 |
-
"re",
|
| 27 |
-
"math",
|
| 28 |
-
"os",
|
| 29 |
-
"requests",
|
| 30 |
-
"csv",
|
| 31 |
-
"urllib",
|
| 32 |
-
"io",
|
| 33 |
-
"cv2",
|
| 34 |
-
]
|
| 35 |
-
|
| 36 |
-
model = select_model("mistral")
|
| 37 |
-
|
| 38 |
-
# MODEL = LiteLLMModel(
|
| 39 |
-
# model_id="google/gemini-2.5-pro-exp-03-25", # Can try diffrent model here I am using qwen2.5 7B model
|
| 40 |
-
# api_key=OPENROUTER_API_KEY,
|
| 41 |
-
# )
|
| 42 |
-
|
| 43 |
-
tools = [
|
| 44 |
-
DuckDuckGoSearchTool(),
|
| 45 |
-
PythonInterpreterTool(),
|
| 46 |
-
WikipediaSearchTool(),
|
| 47 |
save_and_read_file,
|
| 48 |
analyze_excel_file,
|
| 49 |
analyze_csv_file,
|
| 50 |
download_file_from_url,
|
| 51 |
-
|
| 52 |
-
# add,
|
| 53 |
-
# subtract,
|
| 54 |
-
# divide,
|
| 55 |
-
# modulus,
|
| 56 |
-
]
|
| 57 |
-
|
| 58 |
-
verbose = False
|
| 59 |
-
|
| 60 |
-
AGENT = CodeAgent(
|
| 61 |
-
tools=tools,
|
| 62 |
-
model=model,
|
| 63 |
-
additional_authorized_imports=imports,
|
| 64 |
-
executor_type="local",
|
| 65 |
-
executor_kwargs={},
|
| 66 |
-
verbosity_level=2 if verbose else 0,
|
| 67 |
)
|
| 68 |
|
| 69 |
-
# MODEL = LiteLLMModel(
|
| 70 |
-
# model_id="google/gemini-2.5-pro-exp-03-25", # Can try diffrent model here I am using qwen2.5 7B model
|
| 71 |
-
# api_key=OPENROUTER_API_KEY,
|
| 72 |
-
# )
|
| 73 |
-
|
| 74 |
|
| 75 |
class BasicAgent:
|
| 76 |
-
def __init__(
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
self.agent = CodeAgent(
|
| 83 |
tools=tools,
|
| 84 |
-
model=
|
| 85 |
-
additional_authorized_imports=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
executor_type="local",
|
| 87 |
executor_kwargs={},
|
| 88 |
-
verbosity_level=
|
| 89 |
)
|
|
|
|
| 90 |
|
| 91 |
def __call__(self, question: str) -> str:
|
| 92 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 93 |
fixed_answer = "This is a default answer."
|
| 94 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 95 |
return fixed_answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
from smolagents import (
|
| 4 |
CodeAgent,
|
| 5 |
PythonInterpreterTool,
|
|
|
|
| 8 |
)
|
| 9 |
from models import select_model
|
| 10 |
|
| 11 |
+
from typing import Optional
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
from tools import (
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
save_and_read_file,
|
| 15 |
analyze_excel_file,
|
| 16 |
analyze_csv_file,
|
| 17 |
download_file_from_url,
|
| 18 |
+
extract_text_from_image,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
)
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
class BasicAgent:
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
verbose=False,
|
| 26 |
+
name_model_provider="mistral",
|
| 27 |
+
name_model=None,
|
| 28 |
+
):
|
| 29 |
+
self.verbose = verbose
|
| 30 |
+
tools = [
|
| 31 |
+
DuckDuckGoSearchTool(),
|
| 32 |
+
PythonInterpreterTool(),
|
| 33 |
+
WikipediaSearchTool(),
|
| 34 |
+
save_and_read_file,
|
| 35 |
+
analyze_excel_file,
|
| 36 |
+
analyze_csv_file,
|
| 37 |
+
download_file_from_url,
|
| 38 |
+
extract_text_from_image,
|
| 39 |
+
]
|
| 40 |
self.agent = CodeAgent(
|
| 41 |
tools=tools,
|
| 42 |
+
model=select_model(name_model_provider, name_model),
|
| 43 |
+
additional_authorized_imports=[
|
| 44 |
+
"pandas",
|
| 45 |
+
"numpy",
|
| 46 |
+
"datetime",
|
| 47 |
+
"json",
|
| 48 |
+
"re",
|
| 49 |
+
"math",
|
| 50 |
+
"os",
|
| 51 |
+
"requests",
|
| 52 |
+
"csv",
|
| 53 |
+
"urllib",
|
| 54 |
+
"io",
|
| 55 |
+
"cv2",
|
| 56 |
+
],
|
| 57 |
executor_type="local",
|
| 58 |
executor_kwargs={},
|
| 59 |
+
verbosity_level=0,
|
| 60 |
)
|
| 61 |
+
print("BasicAgent initialized.")
|
| 62 |
|
| 63 |
def __call__(self, question: str) -> str:
|
| 64 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 65 |
fixed_answer = "This is a default answer."
|
| 66 |
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 67 |
return fixed_answer
|
| 68 |
+
|
| 69 |
+
def answer_question(
|
| 70 |
+
self, question: str, task_file_path: Optional[str] = None
|
| 71 |
+
) -> str:
|
| 72 |
+
"""
|
| 73 |
+
Process a GAIA benchmark question and return the answer
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
question: The question to answer
|
| 77 |
+
task_file_path: Optional path to a file associated with the question
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
The answer to the question
|
| 81 |
+
"""
|
| 82 |
+
try:
|
| 83 |
+
if self.verbose:
|
| 84 |
+
print(f"Processing question: {question}")
|
| 85 |
+
if task_file_path:
|
| 86 |
+
print(f"With associated file: {task_file_path}")
|
| 87 |
+
|
| 88 |
+
# Create a context with file information if available
|
| 89 |
+
context = question
|
| 90 |
+
file_content = None
|
| 91 |
+
|
| 92 |
+
# If there's a file, read it and include its content in the context
|
| 93 |
+
if task_file_path:
|
| 94 |
+
try:
|
| 95 |
+
with open(task_file_path, "r") as f:
|
| 96 |
+
file_content = f.read()
|
| 97 |
+
|
| 98 |
+
# Determine file type from extension
|
| 99 |
+
file_ext = os.path.splitext(task_file_path)[1].lower()
|
| 100 |
+
|
| 101 |
+
context = f""" Question: {question} This question has an associated file. Here is the file content: ```{file_ext} {file_content}```Analyze the file content above to answer the question."""
|
| 102 |
+
|
| 103 |
+
except Exception as file_e:
|
| 104 |
+
context = f""" Question: {question} This question has an associated file at path: {task_file_path}. However, there was an error reading the file: {file_e}. You can still try to answer the question based on the information provided."""
|
| 105 |
+
|
| 106 |
+
# Check for special cases that need specific formatting
|
| 107 |
+
# Reversed text questions
|
| 108 |
+
if question.startswith(".") or ".rewsna eht sa" in question:
|
| 109 |
+
context = f""" This question appears to be in reversed text. Here's the reversed version: {question[::-1]} Now answer the question above. Remember to format your answer exactly as requested. """
|
| 110 |
+
|
| 111 |
+
# Add a prompt to ensure precise answers
|
| 112 |
+
|
| 113 |
+
full_prompt = f"""{context}. When answering, provide ONLY the precise answer requested. Do not include explanations, steps, reasoning, or additional text. Be direct and specific. GAIA benchmark requires exact matching answers. For example, if asked "What is the capital of France?", respond simply with "Paris"."""
|
| 114 |
+
|
| 115 |
+
# rules = "When answering, your answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. 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. If you are asked for a comma separated list, do not include brackets and apply the above rules depending of whether the element to be put in the list is a number or a string."
|
| 116 |
+
|
| 117 |
+
# full_prompt = f"""{context}. {rules}"""
|
| 118 |
+
|
| 119 |
+
# Run the agent with the question
|
| 120 |
+
answer = self.agent.run(full_prompt)
|
| 121 |
+
|
| 122 |
+
# Clean up the answer to ensure it's in the expected format
|
| 123 |
+
# Remove common prefixes that models often add
|
| 124 |
+
answer = self._clean_answer(answer)
|
| 125 |
+
|
| 126 |
+
if self.verbose:
|
| 127 |
+
print(f"Generated answer: {answer}")
|
| 128 |
+
|
| 129 |
+
return answer
|
| 130 |
+
|
| 131 |
+
except Exception as e:
|
| 132 |
+
error_msg = f"Error answering question: {e}"
|
| 133 |
+
if self.verbose:
|
| 134 |
+
print(error_msg)
|
| 135 |
+
return error_msg
|
| 136 |
+
|
| 137 |
+
def _clean_answer(self, answer: any) -> str:
|
| 138 |
+
"""
|
| 139 |
+
Clean up the answer to remove common prefixes and formatting
|
| 140 |
+
that models often add but that can cause exact match failures.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
answer: The raw answer from the model
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
The cleaned answer as a string
|
| 147 |
+
"""
|
| 148 |
+
# Convert non-string types to strings
|
| 149 |
+
if not isinstance(answer, str):
|
| 150 |
+
# Handle numeric types (float, int)
|
| 151 |
+
if isinstance(answer, float):
|
| 152 |
+
# Format floating point numbers properly
|
| 153 |
+
# Check if it's an integer value in float form (e.g., 12.0)
|
| 154 |
+
if answer.is_integer():
|
| 155 |
+
formatted_answer = str(int(answer))
|
| 156 |
+
else:
|
| 157 |
+
# For currency values that might need formatting
|
| 158 |
+
if abs(answer) >= 1000:
|
| 159 |
+
formatted_answer = f"${answer:,.2f}"
|
| 160 |
+
else:
|
| 161 |
+
formatted_answer = str(answer)
|
| 162 |
+
return formatted_answer
|
| 163 |
+
elif isinstance(answer, int):
|
| 164 |
+
return str(answer)
|
| 165 |
+
else:
|
| 166 |
+
# For any other type
|
| 167 |
+
return str(answer)
|
| 168 |
+
|
| 169 |
+
# Now we know answer is a string, so we can safely use string methods
|
| 170 |
+
# Normalize whitespace
|
| 171 |
+
answer = answer.strip()
|
| 172 |
+
|
| 173 |
+
# Remove common prefixes and formatting that models add
|
| 174 |
+
prefixes_to_remove = [
|
| 175 |
+
"The answer is ",
|
| 176 |
+
"Answer: ",
|
| 177 |
+
"Final answer: ",
|
| 178 |
+
"The result is ",
|
| 179 |
+
"To answer this question: ",
|
| 180 |
+
"Based on the information provided, ",
|
| 181 |
+
"According to the information: ",
|
| 182 |
+
]
|
| 183 |
+
|
| 184 |
+
for prefix in prefixes_to_remove:
|
| 185 |
+
if answer.startswith(prefix):
|
| 186 |
+
answer = answer[len(prefix) :].strip()
|
| 187 |
+
|
| 188 |
+
# Remove quotes if they wrap the entire answer
|
| 189 |
+
if (answer.startswith('"') and answer.endswith('"')) or (
|
| 190 |
+
answer.startswith("'") and answer.endswith("'")
|
| 191 |
+
):
|
| 192 |
+
answer = answer[1:-1].strip()
|
| 193 |
+
|
| 194 |
+
return answer
|
models.py
CHANGED
|
@@ -29,7 +29,5 @@ def select_model(provider, name_model=None):
|
|
| 29 |
print("Invalid command.")
|
| 30 |
|
| 31 |
return LiteLLMModel(
|
| 32 |
-
model_id=f"{provider}/{reference_model}",
|
| 33 |
-
api_key=api_key,
|
| 34 |
-
temperature=0.2,
|
| 35 |
)
|
|
|
|
| 29 |
print("Invalid command.")
|
| 30 |
|
| 31 |
return LiteLLMModel(
|
| 32 |
+
model_id=f"{provider}/{reference_model}", api_key=api_key
|
|
|
|
|
|
|
| 33 |
)
|
tools.py
CHANGED
|
@@ -8,59 +8,32 @@ from urllib.parse import urlparse
|
|
| 8 |
|
| 9 |
|
| 10 |
@tool
|
| 11 |
-
def
|
| 12 |
-
"""Multiply two numbers.
|
| 13 |
-
Args:
|
| 14 |
-
a: first int
|
| 15 |
-
b: second int
|
| 16 |
"""
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
@tool
|
| 21 |
-
def add(a: int, b: int) -> int:
|
| 22 |
-
"""Add two numbers.
|
| 23 |
|
| 24 |
Args:
|
| 25 |
-
|
| 26 |
-
b: second int
|
| 27 |
-
"""
|
| 28 |
-
return a + b
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
@tool
|
| 32 |
-
def subtract(a: int, b: int) -> int:
|
| 33 |
-
"""Subtract two numbers.
|
| 34 |
-
|
| 35 |
-
Args:
|
| 36 |
-
a: first int
|
| 37 |
-
b: second int
|
| 38 |
-
"""
|
| 39 |
-
return a - b
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def divide(a: int, b: int) -> int:
|
| 44 |
-
"""Divide two numbers.
|
| 45 |
-
|
| 46 |
-
Args:
|
| 47 |
-
a: first int
|
| 48 |
-
b: second int
|
| 49 |
"""
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
| 53 |
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
"""Get the modulus of two numbers.
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
|
| 65 |
|
| 66 |
@tool
|
|
|
|
| 8 |
|
| 9 |
|
| 10 |
@tool
|
| 11 |
+
def extract_text_from_image(image_path: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
"""
|
| 13 |
+
Extract text from an image using pytesseract (if available).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
Args:
|
| 16 |
+
image_path: Path to the image file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
Returns:
|
| 19 |
+
Extracted text or error message
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
"""
|
| 21 |
+
try:
|
| 22 |
+
# Try to import pytesseract
|
| 23 |
+
import pytesseract
|
| 24 |
+
from PIL import Image
|
| 25 |
|
| 26 |
+
# Open the image
|
| 27 |
+
image = Image.open(image_path)
|
| 28 |
|
| 29 |
+
# Extract text
|
| 30 |
+
text = pytesseract.image_to_string(image)
|
|
|
|
| 31 |
|
| 32 |
+
return f"Extracted text from image:\n\n{text}"
|
| 33 |
+
except ImportError:
|
| 34 |
+
return "Error: pytesseract is not installed. Please install it with 'pip install pytesseract' and ensure Tesseract OCR is installed on your system."
|
| 35 |
+
except Exception as e:
|
| 36 |
+
return f"Error extracting text from image: {str(e)}"
|
| 37 |
|
| 38 |
|
| 39 |
@tool
|