added new files for model, tools, misc, and agent
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495from smolagents import ( CodeAgent, PythonInterpreterTool, DuckDuckGoSearchTool, WikipediaSearchTool,)from models import select_model
from tools import ( save_and_read_file, analyze_excel_file, analyze_csv_file, download_file_from_url, multiply, add, subtract, divide, modulus,)
imports = [ "pandas", "numpy", "datetime", "json", "re", "math", "os", "requests", "csv", "urllib", "io", "cv2",]
model = select_model("mistral")
# MODEL = LiteLLMModel(# model_id="google/gemini-2.5-pro-exp-03-25", # Can try diffrent model here I am using qwen2.5 7B model# api_key=OPENROUTER_API_KEY,# )
tools = [ DuckDuckGoSearchTool(), PythonInterpreterTool(), WikipediaSearchTool(), save_and_read_file, analyze_excel_file, analyze_csv_file, download_file_from_url, # multiply, # add, # subtract, # divide, # modulus,]
verbose = False
AGENT = CodeAgent( tools=tools, model=model, additional_authorized_imports=imports, executor_type="local", executor_kwargs={}, verbosity_level=2 if verbose else 0,)
# MODEL = LiteLLMModel(# model_id="google/gemini-2.5-pro-exp-03-25", # Can try diffrent model here I am using qwen2.5 7B model# api_key=OPENROUTER_API_KEY,# )
class BasicAgent: def __init__(self): print("BasicAgent initialized.") self.temperature = 0.2 self.verbose = True self.name_model_provider = "mistral" self.name_model = None self.agent = CodeAgent( tools=tools, model=model, additional_authorized_imports=imports, executor_type="local", executor_kwargs={}, verbosity_level=2 if verbose else 0, )
def __call__(self, question: str) -> str: print(f"Agent received question (first 50 chars): {question[:50]}...") fixed_answer = "This is a default answer." print(f"Agent returning fixed answer: {fixed_answer}") return fixed_answer123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143import os
import tempfilefrom typing import Optional
def save_test_file(task_id: str, content: str) -> str: """Save a test file to a temporary location.""" temp_dir = tempfile.gettempdir() file_path = os.path.join(temp_dir, f"test_file_{task_id}.csv")
with open(file_path, "w") as f: f.write(content)
return file_path
def answer_question( agent, verbose, question: str, task_file_path: Optional[str] = None) -> str: """ Process a GAIA benchmark question and return the answer
Args: question: The question to answer task_file_path: Optional path to a file associated with the question
Returns: The answer to the question """ try: if verbose: print(f"Processing question: {question}") if task_file_path: print(f"With associated file: {task_file_path}")
# Create a context with file information if available context = question file_content = None
# If there's a file, read it and include its content in the context if task_file_path: try: with open(task_file_path, "r") as f: file_content = f.read()
# Determine file type from extension file_ext = os.path.splitext(task_file_path)[1].lower()
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."""
except Exception as file_e: 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."""
# Check for special cases that need specific formatting # Reversed text questions if question.startswith(".") or ".rewsna eht sa" in question: 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. """
# Add a prompt to ensure precise answers 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."
# 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"."""
full_prompt = f"""{context}. {rules}"""
# Run the agent with the question answer = agent.run(full_prompt)
# Clean up the answer to ensure it's in the expected format # Remove common prefixes that models often add answer = _clean_answer(answer)
if verbose: print(f"Generated answer: {answer}")
return answer
except Exception as e: error_msg = f"Error answering question: {e}" if verbose: print(error_msg) return error_msg
def _clean_answer(answer: any) -> str: """ Clean up the answer to remove common prefixes and formatting that models often add but that can cause exact match failures.
Args: answer: The raw answer from the model
Returns: The cleaned answer as a string """ # Convert non-string types to strings if not isinstance(answer, str): # Handle numeric types (float, int) if isinstance(answer, float): # Format floating point numbers properly # Check if it's an integer value in float form (e.g., 12.0) if answer.is_integer(): formatted_answer = str(int(answer)) else: # For currency values that might need formatting if abs(answer) >= 1000: formatted_answer = f"${answer:,.2f}" else: formatted_answer = str(answer) return formatted_answer elif isinstance(answer, int): return str(answer) else: # For any other type return str(answer)
# Now we know answer is a string, so we can safely use string methods # Normalize whitespace answer = answer.strip()
# Remove common prefixes and formatting that models add prefixes_to_remove = [ "The answer is ", "Answer: ", "Final answer: ", "The result is ", "To answer this question: ", "Based on the information provided, ", "According to the information: ", ]
for prefix in prefixes_to_remove: if answer.startswith(prefix): answer = answer[len(prefix) :].strip()
# Remove quotes if they wrap the entire answer if (answer.startswith('"') and answer.endswith('"')) or ( answer.startswith("'") and answer.endswith("'") ): answer = answer[1:-1].strip()
return answer1234567891011121314151617181920212223242526272829303132333435from smolagents import LiteLLMModelfrom env import OPENROUTER_API_KEY, GROQ_API_KEY, MISTRAL_API_KEY
def select_model(provider, name_model=None): match provider: case "mistral": reference_model = "mistral-small-latest" api_key = MISTRAL_API_KEY case "openrouter": match name_model: case "gemini": reference_model = "google/gemini-2.5-pro-exp-03-25" case "deepseek": reference_model = "deepseek/deepseek-chat-v3-0324:free" case _: print("Invalid command.") api_key = OPENROUTER_API_KEY case "groq": match name_model: case "llama": reference_model = "llama-3.3-70b-versatile" case "deepseek": reference_model = "deepseek-r1-distill-llama-70b" case _: print("Invalid command.") api_key = GROQ_API_KEY case _: print("Invalid command.")
return LiteLLMModel( model_id=f"{provider}/{reference_model}", api_key=api_key, temperature=0.2, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197import osimport requestsimport tempfile
from smolagents import toolfrom typing import Optionalfrom urllib.parse import urlparse
@tooldef multiply(a: int, b: int) -> int: """Multiply two numbers. Args: a: first int b: second int """ return a * b
@tooldef add(a: int, b: int) -> int: """Add two numbers.
Args: a: first int b: second int """ return a + b
@tooldef subtract(a: int, b: int) -> int: """Subtract two numbers.
Args: a: first int b: second int """ return a - b
@tooldef divide(a: int, b: int) -> int: """Divide two numbers.
Args: a: first int b: second int """ if b == 0: raise ValueError("Cannot divide by zero.") return a / b
@tooldef modulus(a: int, b: int) -> int: """Get the modulus of two numbers.
Args: a: first int b: second int """ return a % b
@tooldef save_and_read_file(content: str, filename: Optional[str] = None) -> str: """ Save content to a temporary file and return the path. Useful for processing files from the GAIA API.
Args: content: The content to save to the file filename: Optional filename, will generate a random name if not provided
Returns: Path to the saved file """ temp_dir = tempfile.gettempdir() if filename is None: temp_file = tempfile.NamedTemporaryFile(delete=False) filepath = temp_file.name else: filepath = os.path.join(temp_dir, filename)
# Write content to the file with open(filepath, "w") as f: f.write(content)
return f"File saved to {filepath}. You can read this file to process its contents."
@tooldef download_file_from_url(url: str, filename: Optional[str] = None) -> str: """ Download a file from a URL and save it to a temporary location.
Args: url: The URL to download from filename: Optional filename, will generate one based on URL if not provided
Returns: Path to the downloaded file """ try: # Parse URL to get filename if not provided if not filename: path = urlparse(url).path filename = os.path.basename(path) if not filename: # Generate a random name if we couldn't extract one import uuid
filename = f"downloaded_{uuid.uuid4().hex[:8]}"
# Create temporary file temp_dir = tempfile.gettempdir() filepath = os.path.join(temp_dir, filename)
# Download the file response = requests.get(url, stream=True) response.raise_for_status()
# Save the file with open(filepath, "wb") as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk)
return f"File downloaded to {filepath}. You can now process this file." except Exception as e: return f"Error downloading file: {str(e)}"
@tooldef analyze_csv_file(file_path: str, query: str) -> str: """ Analyze a CSV file using pandas and answer a question about it.
Args: file_path: Path to the CSV file query: Question about the data
Returns: Analysis result or error message """ try: import pandas as pd
# Read the CSV file df = pd.read_csv(file_path)
# Run various analyses based on the query result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n" result += f"Columns: {', '.join(df.columns)}\n\n"
# Add summary statistics result += "Summary statistics:\n" result += str(df.describe())
return result except ImportError: return "Error: pandas is not installed. Please install it with 'pip install pandas'." except Exception as e: return f"Error analyzing CSV file: {str(e)}"
@tooldef analyze_excel_file(file_path: str, query: str) -> str: """ Analyze an Excel file using pandas and answer a question about it.
Args: file_path: Path to the Excel file query: Question about the data
Returns: Analysis result or error message """ try: import pandas as pd
# Read the Excel file df = pd.read_excel(file_path)
# Run various analyses based on the query result = f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n" result += f"Columns: {', '.join(df.columns)}\n\n"
# Add summary statistics result += "Summary statistics:\n" result += str(df.describe())
return result except ImportError: return "Error: pandas and openpyxl are not installed. Please install them with 'pip install pandas openpyxl'." except Exception as e: return f"Error analyzing Excel file: {str(e)}"agent.pyAdded+95
misc.pyAdded+143
models.pyAdded+35
tools.pyAdded+197