File size: 12,246 Bytes
8e01d85
 
 
 
 
 
 
 
 
ebb5880
 
8e01d85
 
ebb5880
 
 
 
 
 
 
 
 
 
 
 
 
 
8e01d85
ebb5880
8e01d85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebb5880
 
 
 
 
 
 
 
 
 
 
 
 
 
8e01d85
ebb5880
8e01d85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebb5880
 
 
 
 
 
 
 
 
 
 
 
 
 
8e01d85
ebb5880
8e01d85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebb5880
 
 
 
 
 
 
 
 
 
 
 
 
 
8e01d85
ebb5880
8e01d85
 
 
 
 
 
 
 
 
 
ebb5880
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e01d85
ebb5880
8e01d85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebb5880
 
8e01d85
 
 
 
 
 
 
 
 
 
ebb5880
8e01d85
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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)}"