added new files for model, tools, misc, and agent
Browse files
agent.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from smolagents import (
|
| 2 |
+
CodeAgent,
|
| 3 |
+
PythonInterpreterTool,
|
| 4 |
+
DuckDuckGoSearchTool,
|
| 5 |
+
WikipediaSearchTool,
|
| 6 |
+
)
|
| 7 |
+
from models import select_model
|
| 8 |
+
|
| 9 |
+
from tools import (
|
| 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 |
+
imports = [
|
| 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 |
+
# multiply,
|
| 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__(self):
|
| 77 |
+
print("BasicAgent initialized.")
|
| 78 |
+
self.temperature = 0.2
|
| 79 |
+
self.verbose = True
|
| 80 |
+
self.name_model_provider = "mistral"
|
| 81 |
+
self.name_model = None
|
| 82 |
+
self.agent = CodeAgent(
|
| 83 |
+
tools=tools,
|
| 84 |
+
model=model,
|
| 85 |
+
additional_authorized_imports=imports,
|
| 86 |
+
executor_type="local",
|
| 87 |
+
executor_kwargs={},
|
| 88 |
+
verbosity_level=2 if verbose else 0,
|
| 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
|
misc.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import tempfile
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def save_test_file(task_id: str, content: str) -> str:
|
| 8 |
+
"""Save a test file to a temporary location."""
|
| 9 |
+
temp_dir = tempfile.gettempdir()
|
| 10 |
+
file_path = os.path.join(temp_dir, f"test_file_{task_id}.csv")
|
| 11 |
+
|
| 12 |
+
with open(file_path, "w") as f:
|
| 13 |
+
f.write(content)
|
| 14 |
+
|
| 15 |
+
return file_path
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def answer_question(
|
| 19 |
+
agent, verbose, question: str, task_file_path: Optional[str] = None
|
| 20 |
+
) -> str:
|
| 21 |
+
"""
|
| 22 |
+
Process a GAIA benchmark question and return the answer
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
question: The question to answer
|
| 26 |
+
task_file_path: Optional path to a file associated with the question
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
The answer to the question
|
| 30 |
+
"""
|
| 31 |
+
try:
|
| 32 |
+
if verbose:
|
| 33 |
+
print(f"Processing question: {question}")
|
| 34 |
+
if task_file_path:
|
| 35 |
+
print(f"With associated file: {task_file_path}")
|
| 36 |
+
|
| 37 |
+
# Create a context with file information if available
|
| 38 |
+
context = question
|
| 39 |
+
file_content = None
|
| 40 |
+
|
| 41 |
+
# If there's a file, read it and include its content in the context
|
| 42 |
+
if task_file_path:
|
| 43 |
+
try:
|
| 44 |
+
with open(task_file_path, "r") as f:
|
| 45 |
+
file_content = f.read()
|
| 46 |
+
|
| 47 |
+
# Determine file type from extension
|
| 48 |
+
file_ext = os.path.splitext(task_file_path)[1].lower()
|
| 49 |
+
|
| 50 |
+
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."""
|
| 51 |
+
|
| 52 |
+
except Exception as file_e:
|
| 53 |
+
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."""
|
| 54 |
+
|
| 55 |
+
# Check for special cases that need specific formatting
|
| 56 |
+
# Reversed text questions
|
| 57 |
+
if question.startswith(".") or ".rewsna eht sa" in question:
|
| 58 |
+
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. """
|
| 59 |
+
|
| 60 |
+
# Add a prompt to ensure precise answers
|
| 61 |
+
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."
|
| 62 |
+
|
| 63 |
+
# 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"."""
|
| 64 |
+
|
| 65 |
+
full_prompt = f"""{context}. {rules}"""
|
| 66 |
+
|
| 67 |
+
# Run the agent with the question
|
| 68 |
+
answer = agent.run(full_prompt)
|
| 69 |
+
|
| 70 |
+
# Clean up the answer to ensure it's in the expected format
|
| 71 |
+
# Remove common prefixes that models often add
|
| 72 |
+
answer = _clean_answer(answer)
|
| 73 |
+
|
| 74 |
+
if verbose:
|
| 75 |
+
print(f"Generated answer: {answer}")
|
| 76 |
+
|
| 77 |
+
return answer
|
| 78 |
+
|
| 79 |
+
except Exception as e:
|
| 80 |
+
error_msg = f"Error answering question: {e}"
|
| 81 |
+
if verbose:
|
| 82 |
+
print(error_msg)
|
| 83 |
+
return error_msg
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _clean_answer(answer: any) -> str:
|
| 87 |
+
"""
|
| 88 |
+
Clean up the answer to remove common prefixes and formatting
|
| 89 |
+
that models often add but that can cause exact match failures.
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
answer: The raw answer from the model
|
| 93 |
+
|
| 94 |
+
Returns:
|
| 95 |
+
The cleaned answer as a string
|
| 96 |
+
"""
|
| 97 |
+
# Convert non-string types to strings
|
| 98 |
+
if not isinstance(answer, str):
|
| 99 |
+
# Handle numeric types (float, int)
|
| 100 |
+
if isinstance(answer, float):
|
| 101 |
+
# Format floating point numbers properly
|
| 102 |
+
# Check if it's an integer value in float form (e.g., 12.0)
|
| 103 |
+
if answer.is_integer():
|
| 104 |
+
formatted_answer = str(int(answer))
|
| 105 |
+
else:
|
| 106 |
+
# For currency values that might need formatting
|
| 107 |
+
if abs(answer) >= 1000:
|
| 108 |
+
formatted_answer = f"${answer:,.2f}"
|
| 109 |
+
else:
|
| 110 |
+
formatted_answer = str(answer)
|
| 111 |
+
return formatted_answer
|
| 112 |
+
elif isinstance(answer, int):
|
| 113 |
+
return str(answer)
|
| 114 |
+
else:
|
| 115 |
+
# For any other type
|
| 116 |
+
return str(answer)
|
| 117 |
+
|
| 118 |
+
# Now we know answer is a string, so we can safely use string methods
|
| 119 |
+
# Normalize whitespace
|
| 120 |
+
answer = answer.strip()
|
| 121 |
+
|
| 122 |
+
# Remove common prefixes and formatting that models add
|
| 123 |
+
prefixes_to_remove = [
|
| 124 |
+
"The answer is ",
|
| 125 |
+
"Answer: ",
|
| 126 |
+
"Final answer: ",
|
| 127 |
+
"The result is ",
|
| 128 |
+
"To answer this question: ",
|
| 129 |
+
"Based on the information provided, ",
|
| 130 |
+
"According to the information: ",
|
| 131 |
+
]
|
| 132 |
+
|
| 133 |
+
for prefix in prefixes_to_remove:
|
| 134 |
+
if answer.startswith(prefix):
|
| 135 |
+
answer = answer[len(prefix) :].strip()
|
| 136 |
+
|
| 137 |
+
# Remove quotes if they wrap the entire answer
|
| 138 |
+
if (answer.startswith('"') and answer.endswith('"')) or (
|
| 139 |
+
answer.startswith("'") and answer.endswith("'")
|
| 140 |
+
):
|
| 141 |
+
answer = answer[1:-1].strip()
|
| 142 |
+
|
| 143 |
+
return answer
|
models.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from smolagents import LiteLLMModel
|
| 2 |
+
from env import OPENROUTER_API_KEY, GROQ_API_KEY, MISTRAL_API_KEY
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def select_model(provider, name_model=None):
|
| 6 |
+
match provider:
|
| 7 |
+
case "mistral":
|
| 8 |
+
reference_model = "mistral-small-latest"
|
| 9 |
+
api_key = MISTRAL_API_KEY
|
| 10 |
+
case "openrouter":
|
| 11 |
+
match name_model:
|
| 12 |
+
case "gemini":
|
| 13 |
+
reference_model = "google/gemini-2.5-pro-exp-03-25"
|
| 14 |
+
case "deepseek":
|
| 15 |
+
reference_model = "deepseek/deepseek-chat-v3-0324:free"
|
| 16 |
+
case _:
|
| 17 |
+
print("Invalid command.")
|
| 18 |
+
api_key = OPENROUTER_API_KEY
|
| 19 |
+
case "groq":
|
| 20 |
+
match name_model:
|
| 21 |
+
case "llama":
|
| 22 |
+
reference_model = "llama-3.3-70b-versatile"
|
| 23 |
+
case "deepseek":
|
| 24 |
+
reference_model = "deepseek-r1-distill-llama-70b"
|
| 25 |
+
case _:
|
| 26 |
+
print("Invalid command.")
|
| 27 |
+
api_key = GROQ_API_KEY
|
| 28 |
+
case _:
|
| 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 |
+
)
|
tools.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
import tempfile
|
| 4 |
+
|
| 5 |
+
from smolagents import tool
|
| 6 |
+
from typing import Optional
|
| 7 |
+
from urllib.parse import urlparse
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@tool
|
| 11 |
+
def multiply(a: int, b: int) -> int:
|
| 12 |
+
"""Multiply two numbers.
|
| 13 |
+
Args:
|
| 14 |
+
a: first int
|
| 15 |
+
b: second int
|
| 16 |
+
"""
|
| 17 |
+
return a * b
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@tool
|
| 21 |
+
def add(a: int, b: int) -> int:
|
| 22 |
+
"""Add two numbers.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
a: first int
|
| 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 |
+
@tool
|
| 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 |
+
if b == 0:
|
| 51 |
+
raise ValueError("Cannot divide by zero.")
|
| 52 |
+
return a / b
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@tool
|
| 56 |
+
def modulus(a: int, b: int) -> int:
|
| 57 |
+
"""Get the modulus of two numbers.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
a: first int
|
| 61 |
+
b: second int
|
| 62 |
+
"""
|
| 63 |
+
return a % b
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@tool
|
| 67 |
+
def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
|
| 68 |
+
"""
|
| 69 |
+
Save content to a temporary file and return the path.
|
| 70 |
+
Useful for processing files from the GAIA API.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
content: The content to save to the file
|
| 74 |
+
filename: Optional filename, will generate a random name if not provided
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
Path to the saved file
|
| 78 |
+
"""
|
| 79 |
+
temp_dir = tempfile.gettempdir()
|
| 80 |
+
if filename is None:
|
| 81 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False)
|
| 82 |
+
filepath = temp_file.name
|
| 83 |
+
else:
|
| 84 |
+
filepath = os.path.join(temp_dir, filename)
|
| 85 |
+
|
| 86 |
+
# Write content to the file
|
| 87 |
+
with open(filepath, "w") as f:
|
| 88 |
+
f.write(content)
|
| 89 |
+
|
| 90 |
+
return f"File saved to {filepath}. You can read this file to process its contents."
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@tool
|
| 94 |
+
def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
|
| 95 |
+
"""
|
| 96 |
+
Download a file from a URL and save it to a temporary location.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
url: The URL to download from
|
| 100 |
+
filename: Optional filename, will generate one based on URL if not provided
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
Path to the downloaded file
|
| 104 |
+
"""
|
| 105 |
+
try:
|
| 106 |
+
# Parse URL to get filename if not provided
|
| 107 |
+
if not filename:
|
| 108 |
+
path = urlparse(url).path
|
| 109 |
+
filename = os.path.basename(path)
|
| 110 |
+
if not filename:
|
| 111 |
+
# Generate a random name if we couldn't extract one
|
| 112 |
+
import uuid
|
| 113 |
+
|
| 114 |
+
filename = f"downloaded_{uuid.uuid4().hex[:8]}"
|
| 115 |
+
|
| 116 |
+
# Create temporary file
|
| 117 |
+
temp_dir = tempfile.gettempdir()
|
| 118 |
+
filepath = os.path.join(temp_dir, filename)
|
| 119 |
+
|
| 120 |
+
# Download the file
|
| 121 |
+
response = requests.get(url, stream=True)
|
| 122 |
+
response.raise_for_status()
|
| 123 |
+
|
| 124 |
+
# Save the file
|
| 125 |
+
with open(filepath, "wb") as f:
|
| 126 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 127 |
+
f.write(chunk)
|
| 128 |
+
|
| 129 |
+
return f"File downloaded to {filepath}. You can now process this file."
|
| 130 |
+
except Exception as e:
|
| 131 |
+
return f"Error downloading file: {str(e)}"
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@tool
|
| 135 |
+
def analyze_csv_file(file_path: str, query: str) -> str:
|
| 136 |
+
"""
|
| 137 |
+
Analyze a CSV file using pandas and answer a question about it.
|
| 138 |
+
|
| 139 |
+
Args:
|
| 140 |
+
file_path: Path to the CSV file
|
| 141 |
+
query: Question about the data
|
| 142 |
+
|
| 143 |
+
Returns:
|
| 144 |
+
Analysis result or error message
|
| 145 |
+
"""
|
| 146 |
+
try:
|
| 147 |
+
import pandas as pd
|
| 148 |
+
|
| 149 |
+
# Read the CSV file
|
| 150 |
+
df = pd.read_csv(file_path)
|
| 151 |
+
|
| 152 |
+
# Run various analyses based on the query
|
| 153 |
+
result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
| 154 |
+
result += f"Columns: {', '.join(df.columns)}\n\n"
|
| 155 |
+
|
| 156 |
+
# Add summary statistics
|
| 157 |
+
result += "Summary statistics:\n"
|
| 158 |
+
result += str(df.describe())
|
| 159 |
+
|
| 160 |
+
return result
|
| 161 |
+
except ImportError:
|
| 162 |
+
return "Error: pandas is not installed. Please install it with 'pip install pandas'."
|
| 163 |
+
except Exception as e:
|
| 164 |
+
return f"Error analyzing CSV file: {str(e)}"
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@tool
|
| 168 |
+
def analyze_excel_file(file_path: str, query: str) -> str:
|
| 169 |
+
"""
|
| 170 |
+
Analyze an Excel file using pandas and answer a question about it.
|
| 171 |
+
|
| 172 |
+
Args:
|
| 173 |
+
file_path: Path to the Excel file
|
| 174 |
+
query: Question about the data
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
Analysis result or error message
|
| 178 |
+
"""
|
| 179 |
+
try:
|
| 180 |
+
import pandas as pd
|
| 181 |
+
|
| 182 |
+
# Read the Excel file
|
| 183 |
+
df = pd.read_excel(file_path)
|
| 184 |
+
|
| 185 |
+
# Run various analyses based on the query
|
| 186 |
+
result = f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
| 187 |
+
result += f"Columns: {', '.join(df.columns)}\n\n"
|
| 188 |
+
|
| 189 |
+
# Add summary statistics
|
| 190 |
+
result += "Summary statistics:\n"
|
| 191 |
+
result += str(df.describe())
|
| 192 |
+
|
| 193 |
+
return result
|
| 194 |
+
except ImportError:
|
| 195 |
+
return "Error: pandas and openpyxl are not installed. Please install them with 'pip install pandas openpyxl'."
|
| 196 |
+
except Exception as e:
|
| 197 |
+
return f"Error analyzing Excel file: {str(e)}"
|