Simple_AI_Agent / core_agent.py
vallurimahanth's picture
Update core_agent.py
32e2aa2 verified
Raw History Blame
3.99 kB
from smolagents import (
CodeAgent,
DuckDuckGoSearchTool,
HfApiModel,
LiteLLMModel,
OpenAIServerModel,
PythonInterpreterTool,
tool,
InferenceClientModel
)
import requests
@tool
def save_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 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."
@tool
def 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:
if not fileName:
path=urlparse(url).path
fileName=os.path.basename(path)
if not fileName:
import uuid
fileName= f"downloaded_{uuid.uuid4().hex[:8]}"
temp_dir=tempfile.gettempdir()
filepath=os.path.join(temp_dir,fileName)
#Download the file
response=requests.get(url,stream=True)
response.raise_for_status()
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 the file."
except Exception as e:
return f"Error downloading file: {str(e)}"
@tool
def extract_text_from_image(image_path: str) -> str:
"""
Extract text from an image.
Args:
image_path: Path to the image file
Returns:
Extracted text or error message
"""
try:
from langchain.document_loaders import UnstructuredImageLoader
loader = UnstructuredImageLoader(image_path, strategy="ocr_only")
docs = loader.load()
# Join the text from all documents into a single string
extracted_text = "\n".join(doc.page_content for doc in docs)
return extracted_text
except ImportError:
return "Error: pytesseract is not installed. Please install it with 'pip install pytesseract' and ensure Tesseract OCR is installed on your system."
except Exception as e:
return f"Error extracting text from image: {str(e)}"
@tool
def 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)}"