import os import json import time import requests import pandas as pd from openai import OpenAI from bs4 import BeautifulSoup from smolagents import ToolCallingAgent, Tool from smolagents import Tool class WebSearchTool(Tool): def __init__(self): super().__init__( name="web_search", description="Search the web for information on a query. Useful for finding up-to-date information.", input_schema={ "type": "object", "properties": { "query": { "type": "string", "description": "The search query" } }, "required": ["query"] } ) def _run(self, query): try: # Use a search engine API to get results response = requests.get( f"https://www.google.com/search?q={query}", headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"} ) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') search_results = [] # Extract search results for result in soup.select(".tF2Cxc"): title = result.select_one(".DKV0Md").text if result.select_one(".DKV0Md") else "" link = result.select_one("a")["href"] if result.select_one("a") else "" snippet = result.select_one(".VwiC3b").text if result.select_one(".VwiC3b") else "" if title and link: search_results.append({ "title": title, "link": link, "snippet": snippet }) # Format results into a readable string if search_results: formatted_results = "\n\n".join([ f"Title: {r['title']}\nURL: {r['link']}\nSnippet: {r['snippet']}" for r in search_results[:5] # Limit to top 5 results ]) return f"Search results for '{query}':\n\n{formatted_results}" else: return f"No results found for '{query}'." except Exception as e: return f"Error searching the web: {str(e)}" class WebBrowseTool(Tool): def __init__(self): super().__init__( name="web_browse", description="Browse a specific webpage and extract its content.", input_schema={ "type": "object", "properties": { "url": { "type": "string", "description": "The URL of the webpage to browse" } }, "required": ["url"] } ) def _run(self, url): try: headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36" } response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') # Remove script and style elements for script in soup(["script", "style"]): script.extract() # Get text text = soup.get_text() # Clean up text: break into lines and remove leading and trailing space lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) text = '\n'.join(chunk for chunk in chunks if chunk) # Limit text length to avoid LLM context limitations if len(text) > 8000: text = text[:8000] + "...\n[Content truncated due to length]" return f"Content from {url}:\n\n{text}" except Exception as e: return f"Error accessing {url}: {str(e)}" class ReadFileTool(Tool): def __init__(self): super().__init__( name="read_file", description="Read the content of a file.", input_schema={ "type": "object", "properties": { "file_path": { "type": "string", "description": "The path to the file to read" } }, "required": ["file_path"] } ) def _run(self, file_path): try: if not os.path.exists(file_path): return f"Error: File not found at {file_path}" with open(file_path, 'rb') as f: content = f.read() # Try to decode as text try: text_content = content.decode('utf-8') return f"Content of {file_path}:\n\n{text_content}" except UnicodeDecodeError: # If it's not text, just return info about the binary file return f"Binary file {file_path}, size: {len(content)} bytes" except Exception as e: return f"Error reading file: {str(e)}" class CalculateTool(Tool): def __init__(self): super().__init__( name="calculate", description="Perform a calculation.", input_schema={ "type": "object", "properties": { "expression": { "type": "string", "description": "The mathematical expression to calculate" } }, "required": ["expression"] } ) def _run(self, expression): try: # Be very careful with eval - in production this should be replaced with a safer alternative # like the `simpleeval` library result = eval(expression, {"__builtins__": {}}) return f"Result: {result}" except Exception as e: return f"Error calculating '{expression}': {str(e)}" class AnalyzeExcelTool(Tool): def __init__(self): super().__init__( name="analyze_excel", description="Analyze an Excel file and extract data from it.", input_schema={ "type": "object", "properties": { "file_path": { "type": "string", "description": "The path to the Excel file" }, "query": { "type": "string", "description": "The specific data or analysis you want from the file" } }, "required": ["file_path", "query"] } ) def _run(self, file_path, query): try: if not os.path.exists(file_path): return f"Error: File not found at {file_path}" # Read the Excel file try: df = pd.read_excel(file_path) except Exception as e: # Try with different engine if default fails try: df = pd.read_excel(file_path, engine='openpyxl') except Exception as e2: try: df = pd.read_excel(file_path, engine='xlrd') except Exception as e3: return f"Error reading Excel file: {str(e)}, {str(e2)}, {str(e3)}" # Basic info about the Excel file file_info = f"Excel file contains {len(df.columns)} columns and {len(df)} rows.\n" file_info += f"Columns: {', '.join(df.columns.tolist())}\n" # Sample of the data sample = df.head(5).to_string() # Try to answer specific query about the data query_lower = query.lower() # Handle sum queries if "sum" in query_lower or "total" in query_lower: # Try to identify which column(s) to sum based on the query numeric_cols = df.select_dtypes(include=['number']).columns.tolist() column_sums = {} for col in numeric_cols: column_sums[col] = df[col].sum() sums_info = "Sum of numeric columns:\n" for col, total in column_sums.items(): sums_info += f"Sum of {col}: {total}\n" return f"{file_info}\n\n{sample}\n\n{sums_info}" # Handle filter queries elif "filter" in query_lower or "where" in query_lower or "only" in query_lower: # This is a simple example - in a real implementation, # you would use NLP to understand the filter conditions filter_info = "To filter data, please specify the exact column and condition." return f"{file_info}\n\n{sample}\n\n{filter_info}" # Default response with file overview else: return f"{file_info}\n\nSample data:\n{sample}" except Exception as e: return f"Error analyzing Excel file: {str(e)}" def get_agent_tools(): """Return a list of tools available to the agent.""" return [ WebSearchTool(), WebBrowseTool(), ReadFileTool(), CalculateTool(), AnalyzeExcelTool() ] class SmolAgent: def __init__(self, openrouter_api_key, model="anthropic/claude-3-5-sonnet"): # Setup the OpenAI client with OpenRouter self.client = OpenAI( base_url="https://openrouter.ai/api/v1", api_key=openrouter_api_key, default_headers={ "HTTP-Referer": "https://github.com/neuralconfig/osticket-agent", "X-Title": "Agent Evaluation Tool" } ) self.model = model # Create the Smol Agent with tools system_message = """You are a helpful AI assistant designed to answer questions accurately. When presented with a question: 1. Think carefully about what is being asked 2. Use the provided tools when necessary to gather accurate information 3. Provide clear, concise answers based on the information available 4. Always present your final answer directly without adding 'FINAL ANSWER:' or similar phrases 5. If you use research or external information, incorporate it naturally into your response Be precise and focus only on answering the question asked. Do not add disclaimers, avoid hallucinating information, and acknowledge when you don't know something.""" self.agent = ToolCallingAgent( model=self.model, tools=get_agent_tools(), system=system_message, client=self.client ) def __call__(self, question, context=None): """Run the agent on a question and return the answer.""" # Add context about any files if provided if context and "file_path" in context: question += f"\n\nAttached file information: {context.get('file_name', '')}" question += f"\nYou can access this file using the read_file tool with the path: {context.get('file_path')}" try: response = self.agent.run(question) # Make sure we're not including "FINAL ANSWER:" in the response final_answer = response if "FINAL ANSWER:" in final_answer: final_answer = final_answer.split("FINAL ANSWER:", 1)[1].strip() return final_answer except Exception as e: return f"Error processing question: {str(e)}"