File size: 40,938 Bytes
c288490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a437ec2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c288490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a437ec2
 
 
c288490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a437ec2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c288490
 
 
 
 
 
 
 
 
 
 
 
 
80eaceb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d282cd
a437ec2
 
 
 
 
 
80eaceb
c288490
 
 
 
bd83de1
 
 
 
 
 
 
 
 
 
 
 
 
 
c288490
 
5d282cd
 
bd83de1
c288490
 
 
bd83de1
c288490
5d282cd
bd83de1
c288490
5d282cd
c288490
5d282cd
c288490
 
 
 
 
 
 
5d282cd
 
bd83de1
5d282cd
c288490
 
 
bd83de1
c288490
 
5d282cd
 
bd83de1
 
5d282cd
bd83de1
5d282cd
c288490
5d282cd
c288490
 
 
 
5d282cd
bd83de1
c288490
5d282cd
c288490
5d282cd
c288490
 
5d282cd
bd83de1
c288490
5d282cd
c288490
5d282cd
c288490
 
bd83de1
c288490
 
 
 
 
 
 
bd83de1
 
 
 
 
 
 
 
 
 
 
 
 
5d282cd
bd83de1
5d282cd
 
 
 
 
bd83de1
 
5d282cd
 
 
 
bd83de1
 
 
 
 
 
 
5d282cd
 
bd83de1
5d282cd
c288490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d282cd
 
 
 
bd83de1
5d282cd
bd83de1
5d282cd
 
bd83de1
5d282cd
 
 
bd83de1
 
5d282cd
 
c288490
 
 
 
5d282cd
c288490
 
 
 
 
 
 
 
 
 
 
 
 
 
80eaceb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c288490
 
 
 
a437ec2
 
 
 
 
 
 
 
 
 
 
 
 
c288490
80eaceb
 
 
 
 
 
 
 
 
 
 
 
c288490
 
80eaceb
c288490
 
a437ec2
c288490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80eaceb
 
 
 
bd83de1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80eaceb
 
c288490
 
 
 
 
 
 
 
80eaceb
 
c288490
80eaceb
 
c288490
80eaceb
c288490
 
 
 
 
80eaceb
 
c288490
80eaceb
 
c288490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
#!/usr/bin/env python3
import os
import json
import time
import requests
import pandas as pd
from openai import OpenAI
from bs4 import BeautifulSoup
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

class WebSearchTool:
    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 YouTubeTranscriptionTool:
    def run(self, url):
        """Attempt to get a summary or transcript of a YouTube video."""
        try:
            if "youtube.com" not in url and "youtu.be" not in url:
                return f"Error: The URL provided does not appear to be a YouTube link: {url}"
            
            # Extract video ID from the URL
            video_id = None
            if "youtube.com/watch" in url and "v=" in url:
                video_id = url.split("v=")[1].split("&")[0]
            elif "youtu.be/" in url:
                video_id = url.split("youtu.be/")[1].split("?")[0]
            
            if not video_id:
                return f"Error: Could not extract video ID from URL: {url}"
            
            # First, try to get video info from the YouTube API
            video_info_url = f"https://www.googleapis.com/youtube/v3/videos?id={video_id}&part=snippet&key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8"
            
            try:
                response = requests.get(video_info_url)
                response.raise_for_status()
                data = response.json()
                
                if "items" in data and len(data["items"]) > 0:
                    title = data["items"][0]["snippet"]["title"]
                    description = data["items"][0]["snippet"]["description"]
                    channel = data["items"][0]["snippet"]["channelTitle"]
                    published_at = data["items"][0]["snippet"]["publishedAt"]
                    
                    # Try to get transcripts (this is just a fallback as YouTube doesn't provide transcripts via API)
                    web_search = WebSearchTool()
                    transcript_results = web_search.run(f"youtube transcript {title} {channel}")
                    
                    return f"""YouTube Video Information:
Title: {title}
Channel: {channel}
Published: {published_at}
Description: {description[:500]}{"..." if len(description) > 500 else ""}

Video URL: {url}
Video ID: {video_id}

Transcript Search Results:
{transcript_results}
"""
                else:
                    return f"No information found for video ID: {video_id}"
                    
            except Exception as api_error:
                # Fallback to web scraping if the API fails
                try:
                    response = requests.get(url, 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')
                    title = soup.select_one("meta[property='og:title']")["content"] if soup.select_one("meta[property='og:title']") else "Unknown Title"
                    
                    return f"""YouTube Video:
Title: {title}
URL: {url}

I was unable to retrieve the transcript automatically. Here's what you can do:
1. Check if the video has captions available on YouTube
2. Try to find a summary or transcript of this video through a web search
3. Look for information about the video content in the video description or comments
"""
                except Exception as scrape_error:
                    return f"Error extracting YouTube video information: {str(scrape_error)}\nAPI Error: {str(api_error)}"
        
        except Exception as e:
            return f"Error processing YouTube URL: {str(e)}"

class ImageAnalysisTool:
    def run(self, image_url_or_description):
        """Analyze an image or process an image description."""
        try:
            # Check if the input is a URL
            if image_url_or_description.startswith(('http://', 'https://')):
                try:
                    # Try to download the image
                    response = requests.get(image_url_or_description, timeout=10)
                    response.raise_for_status()
                    
                    # Check if it's an image
                    content_type = response.headers.get('Content-Type', '')
                    if 'image' not in content_type:
                        return f"The URL does not point to an image. Content-Type: {content_type}"
                    
                    # For a real implementation, here you would use Vision APIs
                    # Since we can't do that, we'll provide information about the image
                    image_size = len(response.content)
                    return f"""
Image Analysis:
URL: {image_url_or_description}
Size: {image_size} bytes
Content-Type: {content_type}

I can't view the image directly, but based on the URL and metadata, this appears to be a valid image. 
To analyze the specific content, please provide a description of what you see in the image, and I can help interpret it.
"""
                except Exception as url_error:
                    return f"Error accessing image URL: {str(url_error)}"
            else:
                # If it's not a URL, treat it as a description
                return f"""
Based on the description: "{image_url_or_description}"

I'll analyze this as a text description rather than a direct image. If you're describing a chess position, 
please format it using standard chess notation (e.g., FEN notation like "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").

For other types of images, please provide details about what you see in the image, and I can help interpret the content.
"""
        
        except Exception as e:
            return f"Error analyzing image: {str(e)}"

class WebBrowseTool:
    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:
    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:
    def run(self, expression):
        try:
            # Be very careful with eval - in production this should be replaced with a safer alternative
            result = eval(expression, {"__builtins__": {}})
            return f"Result: {result}"
        except Exception as e:
            return f"Error calculating '{expression}': {str(e)}"

class AnalyzeExcelTool:
    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)}"

class DirectAgent:
    def __init__(self, openrouter_api_key=None, model=None):
        self.api_key = openrouter_api_key or os.getenv("OPENROUTER_API_KEY")
        self.model = model or os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")
        
        if not self.api_key:
            raise ValueError("OpenRouter API key not provided and OPENROUTER_API_KEY not set in environment variables.")
        
        # Initialize client
        self.client = OpenAI(
            base_url="https://openrouter.ai/api/v1",
            api_key=self.api_key,
            default_headers={
                "HTTP-Referer": "https://github.com/neuralconfig/agents-course",
                "X-Title": "Agent Evaluation"
            }
        )
        
        # Initialize tools
        self.tools = {
            "web_search": WebSearchTool(),
            "web_browse": WebBrowseTool(),
            "read_file": ReadFileTool(),
            "calculate": CalculateTool(),
            "analyze_excel": AnalyzeExcelTool(),
            "analyze_youtube": YouTubeTranscriptionTool(),
            "analyze_image": ImageAnalysisTool()
        }
        
        # Tool descriptions for the LLM
        self.tool_descriptions = [
            {
                "type": "function",
                "function": {
                    "name": "web_search",
                    "description": "Search the web for information on a given query.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "query": {
                                "type": "string",
                                "description": "The search query"
                            }
                        },
                        "required": ["query"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "web_browse",
                    "description": "Visit a webpage and extract its content.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "url": {
                                "type": "string",
                                "description": "The URL of the webpage to visit"
                            }
                        },
                        "required": ["url"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "read_file",
                    "description": "Read the content of a file.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "file_path": {
                                "type": "string",
                                "description": "The path to the file to read"
                            }
                        },
                        "required": ["file_path"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "calculate",
                    "description": "Perform a calculation.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "expression": {
                                "type": "string",
                                "description": "Mathematical expression to evaluate"
                            }
                        },
                        "required": ["expression"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "analyze_excel",
                    "description": "Analyze an Excel file and extract data.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "file_path": {
                                "type": "string",
                                "description": "Path to the Excel file"
                            },
                            "query": {
                                "type": "string",
                                "description": "What analysis to perform on the data"
                            }
                        },
                        "required": ["file_path", "query"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "analyze_youtube",
                    "description": "Analyze a YouTube video to get information and potentially its transcript.",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "url": {
                                "type": "string",
                                "description": "The YouTube video URL"
                            }
                        },
                        "required": ["url"]
                    }
                }
            },
            {
                "type": "function",
                "function": {
                    "name": "analyze_image",
                    "description": "Analyze an image from a URL or a description of an image (like a chess position).",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "image_url_or_description": {
                                "type": "string",
                                "description": "The URL of the image or a description of the image content"
                            }
                        },
                        "required": ["image_url_or_description"]
                    }
                }
            }
        ]
        
        # System message
        self.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

CRITICAL INSTRUCTION: Your final answer MUST be EXTREMELY minimal. The evaluation system expects the shortest possible answer:
- For "How many..." questions: JUST THE NUMBER with no words (e.g., "2" not "2 albums")
- For name questions: JUST THE NAME with no context (e.g., "John Smith" not "The person is John Smith")
- For date questions: JUST THE DATE with no explanation (e.g., "1995" not "It happened in 1995")
- For "Who..." questions: JUST THE NAME(S) (e.g., "Marie Curie" not "The scientist was Marie Curie")
- For "Where..." questions: JUST THE LOCATION (e.g., "Paris" not "It's located in Paris")
- For sets/lists: JUST THE ITEMS with minimal formatting (e.g., "a,b,c" or "a, b, c")
- For yes/no questions: JUST "Yes" or "No" (not "Yes, because...")

DO NOT INCLUDE:
- Explanations or reasoning
- Your thought process
- Citations or references
- Introductory phrases like "The answer is..."
- Confidence statements like "I believe..."
- Context or background information
- Multiple possible answers (choose the most likely one)

For specialized types of questions:
- For YouTube video questions, use the analyze_youtube tool to get information about the video
- For image or chess position questions, use the analyze_image tool with either the image URL or a description
- For Excel/spreadsheet file questions, use the analyze_excel tool with proper parameters
- When calculations are needed, use the calculate tool to ensure accurate results

THE FINAL ANSWER MUST BE EXTREMELY MINIMAL - think of it as filling in a blank or answering a multiple-choice test. Your reasoning is valuable during your investigation, but your final response should ONLY contain the direct answer with nothing else."""
    
    def _handle_tool_call(self, tool_calls):
        results = []
        
        # ANSI color codes for terminal output
        COLORS = {
            "RED": "\033[91m",
            "GREEN": "\033[92m",
            "YELLOW": "\033[93m",
            "BLUE": "\033[94m",
            "MAGENTA": "\033[95m",
            "CYAN": "\033[96m",
            "WHITE": "\033[97m",
            "BOLD": "\033[1m",
            "RESET": "\033[0m"
        }
        
        print(f"\n{COLORS['BOLD']}{COLORS['YELLOW']}=== TOOL EXECUTION ==={COLORS['RESET']}")
        for tool_call in tool_calls:
            function_name = tool_call.function.name
            tool_call_id = tool_call.id
            
            print(f"{COLORS['BOLD']}EXECUTING TOOL: {COLORS['YELLOW']}{function_name}{COLORS['RESET']} [id: {tool_call_id}]")
            
            try:
                function_args = json.loads(tool_call.function.arguments)
                print(f"{COLORS['YELLOW']}ARGUMENTS:{COLORS['RESET']} {json.dumps(function_args, indent=2)}")
            except Exception as e:
                error_msg = f"Error parsing arguments: {str(e)}"
                print(f"{COLORS['RED']}ERROR:{COLORS['RESET']} {error_msg}")
                results.append({
                    "tool_call_id": tool_call_id,
                    "function_name": function_name,
                    "result": error_msg
                })
                continue
            
            if function_name in self.tools:
                try:
                    # Call the appropriate tool with the arguments
                    if function_name == "analyze_excel":
                        file_path = function_args.get("file_path", "")
                        query = function_args.get("query", "")
                        print(f"{COLORS['YELLOW']}EXCEL ANALYSIS:{COLORS['RESET']} file={file_path}, query={query}")
                        result = self.tools[function_name].run(file_path, query)
                    else:
                        # For all other tools, just pass the first argument
                        first_arg = list(function_args.values())[0] if function_args else ""
                        print(f"{COLORS['YELLOW']}TOOL INPUT [{function_name}]:{COLORS['RESET']} {first_arg}")
                        result = self.tools[function_name].run(first_arg)
                    
                    # Truncate result for logging if it's too long
                    result_preview = result
                    if len(result_preview) > 1000:
                        result_preview = result_preview[:997] + "..."
                    
                    print(f"{COLORS['GREEN']}TOOL RESULT [{function_name}]:{COLORS['RESET']} {result_preview}")
                    
                    results.append({
                        "tool_call_id": tool_call_id,
                        "function_name": function_name,
                        "result": result
                    })
                except Exception as e:
                    error_msg = f"Error executing tool {function_name}: {str(e)}"
                    print(f"{COLORS['RED']}ERROR:{COLORS['RESET']} {error_msg}")
                    results.append({
                        "tool_call_id": tool_call_id,
                        "function_name": function_name,
                        "result": error_msg
                    })
            else:
                error_msg = f"Tool {function_name} not found"
                print(f"{COLORS['RED']}ERROR:{COLORS['RESET']} {error_msg}")
                results.append({
                    "tool_call_id": tool_call_id,
                    "function_name": function_name,
                    "result": error_msg
                })
        
        print(f"{COLORS['YELLOW']}======================={COLORS['RESET']}\n")
        return results
    
    def _call_openrouter_with_retry(self, messages, max_retries=5):
        """Call the OpenRouter API with retry logic for rate limits."""
        retry_count = 0
        base_delay = 2  # Start with a 2-second delay
        
        # ANSI color codes for terminal output
        COLORS = {
            "RED": "\033[91m",
            "GREEN": "\033[92m",
            "YELLOW": "\033[93m",
            "BLUE": "\033[94m",
            "MAGENTA": "\033[95m",
            "CYAN": "\033[96m",
            "WHITE": "\033[97m",
            "BOLD": "\033[1m",
            "RESET": "\033[0m"
        }
        
        # Log the messages being sent to the LLM
        print(f"\n{COLORS['BOLD']}{COLORS['MAGENTA']}=== SENDING TO LLM ==={COLORS['RESET']}")
        for msg in messages:
            role = msg.get("role", "unknown")
            content = msg.get("content", "")
            
            # Truncate content for readability if it's too long
            if content and len(content) > 1000:
                content = content[:997] + "..."
                
            # Handle tool messages specially
            if role == "tool":
                tool_call_id = msg.get("tool_call_id", "unknown")
                print(f"{COLORS['YELLOW']}TOOL RESPONSE [{tool_call_id}]:{COLORS['RESET']} {content}")
            elif role == "system":
                print(f"{COLORS['BLUE']}SYSTEM:{COLORS['RESET']} {content}")
            elif role == "user":
                print(f"{COLORS['GREEN']}USER:{COLORS['RESET']} {content}")
            elif role == "assistant":
                print(f"{COLORS['CYAN']}ASSISTANT:{COLORS['RESET']} {content}")
            else:
                print(f"{role.upper()}: {content}")
        print(f"{COLORS['MAGENTA']}======================={COLORS['RESET']}\n")
        
        while retry_count < max_retries:
            try:
                # Call the API
                response = self.client.chat.completions.create(
                    model=self.model,
                    messages=messages,
                    tools=self.tool_descriptions,
                    tool_choice="auto"
                )
                
                # Check for error object directly in the response
                if hasattr(response, 'error') and response.error:
                    error_code = response.error.get('code')
                    error_msg = response.error.get('message', '')
                    
                    # If it's a rate limit error, retry
                    if error_code == 429 or "rate limit" in error_msg.lower():
                        retry_count += 1
                        delay = base_delay * (2 ** retry_count)  # Exponential backoff
                        print(f"Rate limit hit. Retrying in {delay} seconds...")
                        time.sleep(delay)
                        continue
                
                # If we got a valid response, log it and return it
                if hasattr(response, 'choices') and response.choices and hasattr(response.choices[0], 'message'):
                    message = response.choices[0].message
                    
                    print(f"\n{COLORS['BOLD']}{COLORS['CYAN']}=== LLM RESPONSE ==={COLORS['RESET']}")
                    if hasattr(message, 'content') and message.content:
                        print(f"{COLORS['CYAN']}CONTENT:{COLORS['RESET']} {message.content}")
                    
                    if hasattr(message, 'tool_calls') and message.tool_calls:
                        print(f"{COLORS['BOLD']}{COLORS['YELLOW']}TOOL CALLS [{len(message.tool_calls)}]:{COLORS['RESET']}")
                        for tool_call in message.tool_calls:
                            function_name = tool_call.function.name
                            function_args = tool_call.function.arguments
                            print(f"{COLORS['YELLOW']}  → {function_name}({function_args}){COLORS['RESET']}")
                    print(f"{COLORS['CYAN']}===================={COLORS['RESET']}\n")
                
                # Return the response
                return response
                
            except Exception as e:
                error_msg = str(e).lower()
                print(f"API ERROR: {error_msg}")
                
                # If it's a rate limit error, retry
                if "429" in error_msg or "rate limit" in error_msg:
                    retry_count += 1
                    delay = base_delay * (2 ** retry_count)  # Exponential backoff
                    print(f"Rate limit hit. Retrying in {delay} seconds...")
                    time.sleep(delay)
                else:
                    # For other errors, raise immediately
                    raise
        
        # If we've exhausted retries, raise an exception
        raise Exception(f"Failed after {max_retries} retries due to rate limits")
    
    def _enforce_minimal_answer(self, answer, question):
        """Enforce minimal answer requirements by post-processing the LLM's response."""
        # Check if the answer already looks minimal (very short)
        if len(answer.strip()) <= 20:
            # Already seems minimal, but clean up any extra text
            minimal = answer.strip()
            # Remove phrases like "the answer is"
            for phrase in ["the answer is", "i believe", "i think", "i found", "the result is"]:
                if minimal.lower().startswith(phrase):
                    minimal = minimal[len(phrase):].strip()
                    # Remove any leading colon or punctuation
                    minimal = minimal.lstrip(":,.;").strip()
            return minimal
            
        # Try to extract just the answer based on question type
        question_lower = question.lower()
        
        # For "how many" questions - extract just the number
        if "how many" in question_lower:
            import re
            # Look for numbers in the answer
            numbers = re.findall(r'\b\d+\b', answer)
            if numbers:
                return numbers[0]  # Return the first number found
        
        # For "who" questions - try to extract just the name
        if question_lower.startswith("who"):
            # Look for capitalized words which might be names
            lines = answer.strip().split('\n')
            if len(lines) > 0:
                # Return first line, or if it's too long, first sentence
                first_line = lines[0]
                if len(first_line) > 100:
                    sentences = first_line.split('.')
                    return sentences[0].strip()
                return first_line
                
        # For lists or sets
        if 'subset' in question_lower or 'list' in question_lower or 'set' in question_lower:
            lines = answer.strip().split('\n')
            for line in lines:
                line = line.strip()
                if ',' in line and len(line) < 50:
                    return line
            
            # If we can't find a simple comma-separated list, 
            # look for the last line that might contain the answer
            for line in reversed(lines):
                line = line.strip()
                if line and len(line) < 100:
                    return line
        
        # For yes/no questions
        if question_lower.startswith("is ") or question_lower.startswith("are ") or question_lower.startswith("does ") or question_lower.startswith("can "):
            if "yes" in answer.lower()[:20]:
                return "Yes"
            if "no" in answer.lower()[:20]:
                return "No"
                
        # For questions with obvious lists at the end
        lines = answer.strip().split('\n')
        if len(lines) > 2:
            last_line = lines[-1].strip()
            if last_line and len(last_line) < 100:
                return last_line
        
        # If all else fails, just return the first line/sentence
        lines = answer.strip().split('\n')
        if lines:
            first_line = lines[0].strip()
            if len(first_line) > 100:
                sentences = first_line.split('.')
                return sentences[0].strip()
            return first_line
            
        # Fallback: just return the answer as is
        return answer.strip()
    
    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:
            file_path = context.get("file_path", "")
            file_name = context.get("file_name", "")
            
            # Try to determine the file type
            file_extension = file_path.lower().split(".")[-1] if "." in file_path else ""
            
            if file_extension in ["xlsx", "xls", "csv"]:
                question += f"\n\nAttached file information: {file_name} (Excel/spreadsheet file)"
                question += f"\nYou can analyze this spreadsheet using the analyze_excel tool with the path: {file_path}"
                question += f"\nFor example: analyze_excel('{file_path}', 'What is the total sales?')"
            else:
                question += f"\n\nAttached file information: {file_name}"
                question += f"\nYou can access this file using the read_file tool with the path: {file_path}"
        
        # Add a special instruction to enforce minimal answers
        extra_instruction = """
FINAL REMINDER: Your answer must be MINIMAL. Return ONLY the specific information requested without any explanation.
- For "How many" questions: ONLY return the number
- For "Who/what/where" questions: ONLY return the name/item/location
- For lists: ONLY return the items in a simple comma-separated format (e.g., "A, B, C")
- NEVER include your reasoning, context, or explanations
"""

        # Add the question and special reminder
        user_prompt = f"{question}\n\n{extra_instruction}"
        
        messages = [
            {"role": "system", "content": self.system_message},
            {"role": "user", "content": user_prompt}
        ]
        
        max_steps = 10  # Increased the number of iterations for more complex questions
        
        for step in range(max_steps):
            print(f"Step {step+1}/{max_steps}")
            
            try:
                # Call the API with retry logic
                response = self._call_openrouter_with_retry(messages)
                
                # Debug info
                print(f"Response received, type: {type(response)}")
                
                # Get the response message - with improved error handling
                if not hasattr(response, 'choices') or not response.choices:
                    print("Error: No choices in response")
                    print(f"Full response: {response}")
                    return "Error: Invalid response from OpenRouter API - no choices returned"
                
                # Check if response.choices[0] exists and has a message
                if len(response.choices) == 0 or not hasattr(response.choices[0], 'message'):
                    print("Error: No message in first choice")
                    print(f"Full response: {response}")
                    return "Error: Invalid response from OpenRouter API - no message in first choice"
                
                message = response.choices[0].message
                messages.append(message)
                
                # Check if there are tool calls
                if hasattr(message, 'tool_calls') and message.tool_calls:
                    print(f"Tool calls detected: {len(message.tool_calls)}")
                    
                    # Execute the tool calls
                    tool_results = self._handle_tool_call(message.tool_calls)
                    
                    # Add the tool results to the messages
                    for result in tool_results:
                        tool_message = {
                            "role": "tool",
                            "tool_call_id": result["tool_call_id"],
                            "content": result["result"]
                        }
                        messages.append(tool_message)
                        print(f"Tool {result['function_name']} executed")
                else:
                    # No more tool calls, we have the final answer
                    if not hasattr(message, 'content'):
                        print("Error: Message has no content attribute")
                        return "Error: Invalid response from OpenRouter API - message has no content"
                    
                    # Apply post-processing to extract a minimal answer
                    original_answer = message.content
                    minimal_answer = self._enforce_minimal_answer(original_answer, question)
                    
                    # ANSI color codes for terminal output
                    COLORS = {
                        "RED": "\033[91m",
                        "GREEN": "\033[92m",
                        "YELLOW": "\033[93m",
                        "BLUE": "\033[94m",
                        "MAGENTA": "\033[95m",
                        "CYAN": "\033[96m",
                        "WHITE": "\033[97m",
                        "BOLD": "\033[1m",
                        "RESET": "\033[0m"
                    }
                    
                    print(f"\n{COLORS['BOLD']}{COLORS['WHITE']}=== ANSWER PROCESSING ==={COLORS['RESET']}")
                    print(f"{COLORS['CYAN']}ORIGINAL ANSWER:{COLORS['RESET']}\n{original_answer}")
                    print(f"\n{COLORS['BOLD']}{COLORS['GREEN']}MINIMAL ANSWER:{COLORS['RESET']} {minimal_answer}")
                    print(f"{COLORS['WHITE']}========================={COLORS['RESET']}\n")
                    
                    return minimal_answer
            
            except Exception as e:
                print(f"Error in step {step+1}: {str(e)}")
                
                # Try to recover and continue with what we have
                if messages and len(messages) > 2:
                    last_message = messages[-1]
                    if isinstance(last_message, dict) and 'content' in last_message:
                        content = last_message['content']
                        return self._enforce_minimal_answer(content, question)
                    elif hasattr(last_message, 'content') and last_message.content:
                        content = last_message.content
                        return self._enforce_minimal_answer(content, question)
                
                return f"Error: {str(e)}"
        
        # If we've reached the maximum number of steps, return the last message
        if messages and len(messages) > 1:
            last_message = messages[-1]
            if isinstance(last_message, dict) and 'content' in last_message:
                content = last_message['content']
                return self._enforce_minimal_answer(content, question)
            elif hasattr(last_message, 'content') and last_message.content:
                content = last_message.content
                return self._enforce_minimal_answer(content, question)
        
        return "Error: Reached maximum steps without getting a final answer"

# Test code
if __name__ == "__main__":
    # Get model from environment variables or default to Claude
    model = os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")
    print(f"\n=== Testing with model from .env: {model} ===\n")
    
    # Create the agent with the model from .env
    agent = DirectAgent()
    
    # Test questions
    questions = [
        "What is the capital of France?",
        "What is 25 * 4 + 10?",
        "What is the largest mammal on Earth?"
    ]
    
    # Test each question
    for question in questions:
        print(f"\nQuestion: {question}")
        try:
            answer = agent(question)
            print(f"\nAnswer: {answer}")
        except Exception as e:
            print(f"\nError: {str(e)}")
    
    print("\n=== Testing complete ===")