File size: 37,184 Bytes
90d7802
 
 
 
 
 
 
 
 
 
 
 
 
e365088
 
 
 
90d7802
 
 
 
 
 
 
 
 
 
e365088
 
 
 
 
 
90d7802
e365088
90d7802
 
 
 
e365088
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90d7802
e365088
 
 
 
 
 
 
90d7802
e365088
90d7802
 
 
 
 
 
e365088
90d7802
 
 
 
e365088
 
 
 
90d7802
e365088
 
 
 
 
90d7802
e365088
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90d7802
e365088
 
 
 
 
 
 
 
 
90d7802
e365088
 
 
90d7802
e365088
 
 
 
 
 
 
 
 
90d7802
e365088
 
 
 
 
 
90d7802
 
e365088
 
90d7802
e365088
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90d7802
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e365088
90d7802
 
 
e365088
90d7802
 
e365088
90d7802
e365088
90d7802
e365088
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90d7802
e365088
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90d7802
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Enhanced web search tool with multiple search strategies and advanced scraping.
"""
import os
import re
import json
import requests
import time
import logging
import concurrent.futures
from bs4 import BeautifulSoup
from urllib.parse import quote, urlparse, urlencode, parse_qs
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure logging
logger = logging.getLogger(__name__)

class EnhancedWebSearchTool:
    """
    An advanced web search tool that uses multiple search engines and strategies.
    """
    def __init__(self):
        self.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"
        
        # Get API keys from environment
        self.serper_api_key = os.getenv("SERPER_API_KEY")
        self.serpapi_api_key = os.getenv("SERPAPI_API_KEY")
        
        # Set up search engines - use API methods if keys are available
        self.search_engines = {
            "google": self._search_google_api if self.serper_api_key else self._search_google,
            "duckduckgo": self._search_duckduckgo,
            "bing": self._search_bing,
            "wikipedia": self._search_wikipedia
        }
        
        # Add API-based search engines if keys are available
        if self.serper_api_key:
            self.search_engines["serper"] = self._search_serper_api
            logger.info("Serper API enabled for web search")
        
        if self.serpapi_api_key:
            self.search_engines["serpapi"] = self._search_serpapi
            logger.info("SerpAPI enabled for web search")
            
        # Configure preferred search order based on what's available
        self.search_order = []
        if self.serper_api_key:
            self.search_order.append("serper")
        if self.serpapi_api_key:
            self.search_order.append("serpapi")
        self.search_order.extend(["google", "duckduckgo", "bing", "wikipedia"])
            
        # Create session with reasonable headers
        self.session = requests.Session()
        self.session.headers.update({
            "User-Agent": self.user_agent,
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Accept-Language": "en-US,en;q=0.5",
            "Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1"
        })
        
    def search(self, query, max_results=5, search_engine=None):
        """
        Search the web for information.
        
        Args:
            query (str): The search query
            max_results (int): Maximum number of results to return
            search_engine (str): Search engine to use (None for automatic selection)
            
        Returns:
            str: Formatted search results or error message
        """
        # If no search engine specified, use the first one in our preferred order
        if search_engine is None:
            search_engine = self.search_order[0] if self.search_order else "google"
            
        if search_engine not in self.search_engines:
            logger.warning(f"Unsupported search engine: {search_engine}, falling back to preferred order")
            search_engine = self.search_order[0] if self.search_order else "google"
            
        # Record all errors we encounter
        all_errors = []
        
        # Try the search using our preferred order
        for engine in [search_engine] + [e for e in self.search_order if e != search_engine]:
            try:
                logger.info(f"Searching with {engine} for: {query}")
                results = self.search_engines[engine](query, max_results)
                
                if results.get("results"):
                    # We found results, format and return them
                    logger.info(f"Found results with {engine}")
                    formatted_results = self._format_results(results, query)
                    
                    # Check if meaningful results were found
                    if "No results found" not in formatted_results:
                        return formatted_results
            except Exception as e:
                error_msg = f"Error with {engine} search: {str(e)}"
                logger.warning(error_msg)
                all_errors.append(error_msg)
                continue  # Try the next engine
        
        # If we reach here, we haven't found results with any engine
        # Try with a simplified query
        simplified_query = self._simplify_query(query)
        if simplified_query != query:
            logger.info(f"Trying simplified query: {simplified_query}")
            # Start again with the preferred search order
            for engine in self.search_order:
                try:
                    results = self.search_engines[engine](simplified_query, max_results)
                    if results.get("results"):
                        logger.info(f"Found results with {engine} using simplified query")
                        return self._format_results(results, simplified_query)
                except Exception as e:
                    logger.warning(f"Error with {engine} simplified search: {str(e)}")
                    continue  # Try the next engine
        
        # If we still have no results, return a helpful error message
        logger.error(f"All search engines failed for query: {query}")
        return f"No results found for '{query}'. Multiple search engines were tried but none returned relevant information."
    
    def _search_serper_api(self, query, max_results=5):
        """
        Search using the Serper.dev API (Google search API).
        
        Args:
            query (str): Search query
            max_results (int): Maximum number of results to return
            
        Returns:
            dict: Dictionary with search results
        """
        try:
            url = "https://google.serper.dev/search"
            headers = {
                "X-API-KEY": self.serper_api_key,
                "Content-Type": "application/json"
            }
            payload = {
                "q": query,
                "num": max_results
            }
            
            response = requests.post(url, headers=headers, json=payload, timeout=10)
            response.raise_for_status()
            data = response.json()
            
            # Extract organic results
            results = []
            if "organic" in data:
                for item in data["organic"][:max_results]:
                    results.append({
                        "title": item.get("title", ""),
                        "link": item.get("link", ""),
                        "snippet": item.get("snippet", "")
                    })
            
            return {
                "query": query,
                "results": results,
                "search_engine": "serper",
                "total_results": len(results)
            }
            
        except Exception as e:
            logger.error(f"Error with Serper API search: {str(e)}")
            raise
    
    def _search_serpapi(self, query, max_results=5):
        """
        Search using the SerpAPI.
        
        Args:
            query (str): Search query
            max_results (int): Maximum number of results to return
            
        Returns:
            dict: Dictionary with search results
        """
        try:
            params = {
                "q": query,
                "api_key": self.serpapi_api_key,
                "num": max_results
            }
            
            url = f"https://serpapi.com/search?{urlencode(params)}"
            response = requests.get(url, timeout=10)
            response.raise_for_status()
            data = response.json()
            
            # Extract organic results
            results = []
            if "organic_results" in data:
                for item in data["organic_results"][:max_results]:
                    results.append({
                        "title": item.get("title", ""),
                        "link": item.get("link", ""),
                        "snippet": item.get("snippet", "")
                    })
            
            return {
                "query": query,
                "results": results,
                "search_engine": "serpapi",
                "total_results": len(results)
            }
            
        except Exception as e:
            logger.error(f"Error with SerpAPI search: {str(e)}")
            raise
    
    def _search_google_api(self, query, max_results=5):
        """
        Search using the Serper API specifically for Google results.
        This is an alias for _search_serper_api for compatibility.
        """
        return self._search_serper_api(query, max_results)

    def _simplify_query(self, query):
        """Simplify a complex query to increase chances of finding results."""
        # Remove special characters that might be causing issues
        simplified = re.sub(r'[^\w\s]', ' ', query)
        simplified = re.sub(r'\s+', ' ', simplified).strip()
        
        # Remove very specific dates or numbers if present
        simplified = re.sub(r'\b\d{1,2}/\d{1,2}/\d{2,4}\b', '', simplified)
        
        # If query is about a person, try to extract just the name
        if 'who' in query.lower():
            name_match = re.search(r'([A-Z][a-z]+ [A-Z][a-z]+)', query)
            if name_match:
                return name_match.group(1)
        
        # If query is very long, take just the key parts
        if len(simplified.split()) > 10:
            # Extract key nouns and names (capitalized words are often important)
            important_words = re.findall(r'\b[A-Z][a-z]+\b', query)
            if len(important_words) >= 2:
                return ' '.join(important_words)
        
        # Add "wikipedia" to the query if it might be an encyclopedia question
        if any(word in query.lower() for word in ['who', 'what', 'when', 'where', 'why']):
            if 'wikipedia' not in query.lower():
                return simplified + " wikipedia"
        
        return simplified if simplified != query else query
    
    def _search_google(self, query, max_results=5):
        """Perform a Google search."""
        try:
            url = f"https://www.google.com/search?q={quote(query)}"
            
            try:
                response = self.session.get(url, timeout=10)
                response.raise_for_status()
            except requests.exceptions.RequestException as e:
                logger.warning(f"Google search request failed: {str(e)}")
                # Try with different parameters
                url = f"https://www.google.com/search?{urlencode({'q': query})}"
                response = self.session.get(url, timeout=10)
                response.raise_for_status()
            
            soup = BeautifulSoup(response.text, 'html.parser')
            search_results = []
            
            # Try multiple CSS selectors for Google results (they change frequently)
            selectors = [
                ".tF2Cxc", ".g", ".Gx5Zad", "div.iDjcJe", "div.yuRUbf",
                "div[data-sokoban-container]", ".v5yQqb"
            ]
            
            for selector in selectors:
                results_found = False
                for result in soup.select(selector):
                    # Try different patterns to extract title, link, and snippet
                    title_elem = (
                        result.select_one(".DKV0Md") or 
                        result.select_one("h3") or 
                        result.select_one(".LC20lb")
                    )
                    
                    link_elem = result.select_one("a")
                    
                    snippet_elem = (
                        result.select_one(".VwiC3b") or 
                        result.select_one(".st") or 
                        result.select_one(".UiGGAb") or
                        result.select_one(".lEBKkf")
                    )
                    
                    title = title_elem.text.strip() if title_elem else ""
                    link = link_elem["href"] if link_elem and "href" in link_elem.attrs else ""
                    
                    # Clean up the link (remove Google redirects)
                    if link.startswith("/url?") or "google.com/url" in link:
                        try:
                            query_params = parse_qs(urlparse(link).query)
                            if 'q' in query_params and query_params['q']:
                                link = query_params['q'][0]
                        except:
                            pass
                    
                    snippet = snippet_elem.text.strip() if snippet_elem else ""
                    
                    if title and link and 'google.com/search' not in link:
                        search_results.append({
                            "title": title,
                            "link": link,
                            "snippet": snippet
                        })
                        results_found = True
                
                if results_found:
                    break
            
            # If still no results, try looking for featured snippets
            if not search_results:
                featured_snippet = soup.select_one(".hgKElc") or soup.select_one(".kno-rdesc")
                if featured_snippet:
                    search_results.append({
                        "title": "Featured Snippet",
                        "link": url,
                        "snippet": featured_snippet.text.strip()
                    })
            
            return {
                "search_engine": "google",
                "query": query,
                "results": search_results[:max_results]
            }
        
        except Exception as e:
            logger.error(f"Error in Google search: {str(e)}", exc_info=True)
            return {
                "search_engine": "google",
                "query": query,
                "error": str(e),
                "results": []
            }
    
    def _search_duckduckgo(self, query, max_results=5):
        """Perform a DuckDuckGo search."""
        try:
            url = f"https://html.duckduckgo.com/html/?q={quote(query)}"
            
            response = self.session.get(url, timeout=10)
            response.raise_for_status()
            
            soup = BeautifulSoup(response.text, 'html.parser')
            search_results = []
            
            # Extract search results from DuckDuckGo
            for result in soup.select(".result"):
                title_elem = result.select_one(".result__title")
                link_elem = result.select_one(".result__url")
                snippet_elem = result.select_one(".result__snippet")
                
                title = title_elem.text.strip() if title_elem else ""
                link = link_elem.text.strip() if link_elem else ""
                snippet = snippet_elem.text.strip() if snippet_elem else ""
                
                # Get actual URL from href
                if title_elem and title_elem.find("a"):
                    href = title_elem.find("a").get("href", "")
                    if href:
                        try:
                            # DuckDuckGo uses redirects, extract the actual URL
                            # Parse parameters like 'uddg='
                            if "?" in href:
                                params = dict(pair.split('=') for pair in href.split('?')[1].split('&') if '=' in pair)
                                if 'uddg' in params:
                                    link = params['uddg']
                        except Exception as e:
                            logger.debug(f"Error parsing DuckDuckGo URL: {str(e)}")
                
                if title and (link or href):
                    final_link = link if link else href
                    search_results.append({
                        "title": title,
                        "link": final_link,
                        "snippet": snippet
                    })
            
            # If no results found with the main approach, try an alternative approach
            if not search_results:
                for result in soup.select(".links_main"):
                    title_elem = result.select_one("a")
                    snippet_elem = result.select_one(".result__snippet")
                    
                    if title_elem:
                        title = title_elem.text.strip()
                        href = title_elem.get("href", "")
                        snippet = snippet_elem.text.strip() if snippet_elem else ""
                        
                        if title and href:
                            search_results.append({
                                "title": title,
                                "link": href,
                                "snippet": snippet
                            })
            
            return {
                "search_engine": "duckduckgo",
                "query": query,
                "results": search_results[:max_results]
            }
            
        except Exception as e:
            logger.error(f"Error in DuckDuckGo search: {str(e)}", exc_info=True)
            return {
                "search_engine": "duckduckgo",
                "query": query,
                "error": str(e),
                "results": []
            }
    
    def _search_bing(self, query, max_results=5):
        """Perform a Bing search."""
        try:
            url = f"https://www.bing.com/search?q={quote(query)}"
            
            response = self.session.get(url, timeout=10)
            response.raise_for_status()
            
            soup = BeautifulSoup(response.text, 'html.parser')
            search_results = []
            
            # Extract search results from Bing
            for result in soup.select(".b_algo"):
                title_elem = result.select_one("h2")
                link_elem = result.select_one("a")
                snippet_elem = result.select_one(".b_caption p") or result.select_one(".b_snippet")
                
                title = title_elem.text.strip() if title_elem else ""
                link = link_elem["href"] if link_elem and "href" in link_elem.attrs else ""
                snippet = snippet_elem.text.strip() if snippet_elem else ""
                
                if title and link:
                    search_results.append({
                        "title": title,
                        "link": link,
                        "snippet": snippet
                    })
            
            # If no results found with the main approach, try an alternative approach
            if not search_results:
                for result in soup.select("#b_results > li"):
                    title_elem = result.select_one("h2 a")
                    
                    if title_elem:
                        title = title_elem.text.strip()
                        href = title_elem.get("href", "")
                        
                        # Try to find the snippet in various locations
                        snippet_elem = (
                            result.select_one(".b_caption p") or 
                            result.select_one(".b_snippet") or 
                            result.select_one(".b_richcard") or
                            result.select_one(".b_vPanel")
                        )
                        snippet = snippet_elem.text.strip() if snippet_elem else ""
                        
                        if title and href:
                            search_results.append({
                                "title": title,
                                "link": href,
                                "snippet": snippet
                            })
            
            return {
                "search_engine": "bing",
                "query": query,
                "results": search_results[:max_results]
            }
            
        except Exception as e:
            logger.error(f"Error in Bing search: {str(e)}", exc_info=True)
            return {
                "search_engine": "bing",
                "query": query,
                "error": str(e),
                "results": []
            }
    
    def _search_wikipedia(self, query, max_results=5):
        """Perform a Wikipedia search."""
        try:
            # First search for Wikipedia articles
            search_url = f"https://en.wikipedia.org/w/api.php?action=opensearch&search={quote(query)}&limit={max_results}&namespace=0&format=json"
            
            response = self.session.get(search_url, timeout=10)
            response.raise_for_status()
            
            data = response.json()
            if len(data) < 4:
                return {
                    "search_engine": "wikipedia",
                    "query": query,
                    "error": "Invalid response format from Wikipedia API",
                    "results": []
                }
                
            titles = data[1]
            links = data[3]
            
            if not titles:
                # Try with a simplified query
                simplified_query = re.sub(r'[^\w\s]', ' ', query)
                simplified_query = re.sub(r'\s+', ' ', simplified_query).strip()
                
                if simplified_query != query:
                    search_url = f"https://en.wikipedia.org/w/api.php?action=opensearch&search={quote(simplified_query)}&limit={max_results}&namespace=0&format=json"
                    response = self.session.get(search_url, timeout=10)
                    response.raise_for_status()
                    
                    data = response.json()
                    if len(data) >= 4:
                        titles = data[1]
                        links = data[3]
            
            search_results = []
            
            # Only use ThreadPoolExecutor if we have results to process
            if titles and len(titles) > 0:
                # Process search results in parallel for speed
                with concurrent.futures.ThreadPoolExecutor(max_workers=min(5, max(1, len(titles)))) as executor:
                    future_to_idx = {
                        executor.submit(self._get_wikipedia_snippet, title, link): i
                        for i, (title, link) in enumerate(zip(titles, links)) if i < max_results
                    }
                    
                    for future in concurrent.futures.as_completed(future_to_idx):
                        result = future.result()
                        if result:
                            search_results.append(result)
            
            # Sort results back to original order since they might come back in any order
            search_results.sort(key=lambda x: links.index(x['link']) if x['link'] in links else 999)
            
            return {
                "search_engine": "wikipedia",
                "query": query,
                "results": search_results[:max_results]
            }
            
        except Exception as e:
            logger.error(f"Error in Wikipedia search: {str(e)}", exc_info=True)
            # Try direct article lookup as fallback
            try:
                # Format query to look like a Wikipedia title
                direct_title = query.strip().replace(' ', '_')
                article_url = f"https://en.wikipedia.org/wiki/{quote(direct_title)}"
                
                article_response = self.session.get(article_url, timeout=10)
                
                if article_response.status_code == 200:
                    # Successfully found a direct article
                    soup = BeautifulSoup(article_response.text, 'html.parser')
                    title = soup.select_one("#firstHeading").text.strip() if soup.select_one("#firstHeading") else direct_title
                    
                    # Get the first paragraph
                    paragraphs = soup.select("#mw-content-text p")
                    snippet = ""
                    
                    for p in paragraphs:
                        if p.text.strip():
                            snippet = p.text.strip()
                            break
                    
                    return {
                        "search_engine": "wikipedia",
                        "query": query,
                        "results": [{
                            "title": title,
                            "link": article_url,
                            "snippet": snippet[:250] + "..." if len(snippet) > 250 else snippet
                        }]
                    }
            except Exception as e2:
                logger.error(f"Wikipedia direct lookup also failed: {str(e2)}")
            
            return {
                "search_engine": "wikipedia",
                "query": query,
                "error": str(e),
                "results": []
            }
    
    def _get_wikipedia_snippet(self, title, link):
        """Helper method to get a snippet from a Wikipedia article."""
        try:
            # Extract page title from URL
            page_title = link.split("/wiki/")[1] if "/wiki/" in link else title
            
            # Get article snippet
            snippet_url = f"https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=true&explaintext=true&titles={page_title}&format=json"
            
            snippet_response = self.session.get(snippet_url, timeout=5)
            snippet_data = snippet_response.json()
            
            # Extract snippet from response
            pages = snippet_data.get("query", {}).get("pages", {})
            snippet = ""
            for page_id in pages:
                snippet = pages[page_id].get("extract", "")
                break
            
            return {
                "title": title,
                "link": link,
                "snippet": snippet[:250] + "..." if len(snippet) > 250 else snippet
            }
        except Exception as e:
            logger.warning(f"Error getting Wikipedia snippet for {title}: {str(e)}")
            return {
                "title": title,
                "link": link,
                "snippet": "Error retrieving article snippet."
            }
    
    def _format_results(self, results, query):
        """Format search results into a readable string."""
        search_engine = results.get("search_engine", "unknown")
        
        if "error" in results:
            return f"Error searching for '{query}' on {search_engine}: {results['error']}"
        
        search_results = results.get("results", [])
        
        if not search_results:
            return f"No results found for '{query}' on {search_engine}."
        
        formatted_results = f"Search results for '{query}' from {search_engine.title()}:\n\n"
        
        for i, result in enumerate(search_results, 1):
            formatted_results += f"{i}. {result['title']}\n"
            formatted_results += f"   URL: {result['link']}\n"
            
            if result.get('snippet'):
                # Clean up the snippet to make it more readable
                snippet = result['snippet']
                # Remove excessive whitespace
                snippet = re.sub(r'\s+', ' ', snippet).strip()
                # Remove HTML tags that might have been missed
                snippet = re.sub(r'<[^>]+>', '', snippet)
                
                formatted_results += f"   Summary: {snippet}\n"
            
            formatted_results += "\n"
        
        return formatted_results
    
    def search_with_all_engines(self, query, max_results=3):
        """
        Search with all available engines and combine results.
        
        Args:
            query (str): The search query
            max_results (int): Maximum number of results per engine
            
        Returns:
            str: Combined search results
        """
        combined_results = []
        
        # Use our preferred search order
        for engine in self.search_order:
            try:
                logger.info(f"Searching with {engine} for: {query}")
                results = self.search_engines[engine](query, max_results)
                
                if results.get("results"):
                    engine_results = results["results"][:max_results]
                    
                    # Add source engine to each result
                    for result in engine_results:
                        result["engine"] = engine
                    
                    combined_results.extend(engine_results)
            except Exception as e:
                logger.warning(f"Error with {engine} search: {str(e)}")
        
        # If we found results, format them
        if combined_results:
            # Sort by relevance (assuming first results from each engine are more relevant)
            # and remove duplicates by URL
            seen_urls = set()
            unique_results = []
            
            for result in combined_results:
                url = result.get("link", "")
                if url and url not in seen_urls:
                    seen_urls.add(url)
                    unique_results.append(result)
            
            # Format the results nicely
            formatted_results = f"Combined results for '{query}' from multiple search engines:\n\n"
            
            for i, result in enumerate(unique_results[:max_results*2], 1):
                title = result.get("title", "No title")
                link = result.get("link", "No URL")
                snippet = result.get("snippet", "No description")
                engine = result.get("engine", "unknown")
                
                formatted_results += f"{i}. {title} [{engine}]\n"
                formatted_results += f"   URL: {link}\n"
                formatted_results += f"   Summary: {snippet}\n\n"
            
            return formatted_results
        else:
            return f"No results found for '{query}' across any search engines."
            engine_name = engine_results["engine"].title()
            formatted_results += f"=== Results from {engine_name} ===\n\n"
            
            for i, result in enumerate(engine_results["results"], 1):
                formatted_results += f"{i}. {result['title']}\n"
                formatted_results += f"   URL: {result['link']}\n"
                
                if result.get('snippet'):
                    # Clean up the snippet
                    snippet = result['snippet']
                    snippet = re.sub(r'\s+', ' ', snippet).strip()
                    snippet = re.sub(r'<[^>]+>', '', snippet)
                    
                    formatted_results += f"   Summary: {snippet}\n"
                
                formatted_results += "\n"
        
        return formatted_results
    
    def _safe_search(self, engine_name, query, max_results):
        """Execute a search with error handling for parallel execution."""
        try:
            return self.search_engines[engine_name](query, max_results)
        except Exception as e:
            logger.error(f"Error in {engine_name} search: {str(e)}", exc_info=True)
            return {
                "search_engine": engine_name,
                "query": query,
                "error": str(e),
                "results": []
            }

    def browse_webpage(self, url):
        """
        Browse a webpage and extract its content.
        
        Args:
            url (str): URL of the webpage to browse
            
        Returns:
            str: Extracted content from the webpage
        """
        try:
            max_retries = 3
            retry_delay = 2  # seconds
            
            for attempt in range(max_retries):
                try:
                    response = self.session.get(url, timeout=15)
                    response.raise_for_status()
                    break
                except requests.exceptions.RequestException as e:
                    if attempt == max_retries - 1:
                        raise
                    logger.warning(f"Retry {attempt+1}/{max_retries} failed: {str(e)}")
                    time.sleep(retry_delay)
                    retry_delay *= 2  # Exponential backoff
            
            content_type = response.headers.get('Content-Type', '').lower()
            
            # Check if the response is HTML
            if 'text/html' not in content_type:
                return f"The URL {url} returned non-HTML content (type: {content_type})."
            
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # Remove script, style, and other non-content elements
            for element in soup(["script", "style", "header", "footer", "nav", "aside", "iframe", "noscript"]):
                element.extract()
            
            # Extract the page title
            title = soup.title.string if soup.title else "No title found"
            
            # Try to extract the main content
            main_content = None
            
            # Common selectors for main content
            main_selectors = [
                "main", "article", "#content", ".content", "#main", ".main",
                "[role='main']", "#article", ".article", "#post", ".post"
            ]
            
            for selector in main_selectors:
                content_elements = soup.select(selector)
                if content_elements:
                    main_content = "\n".join(elem.get_text(separator="\n", strip=True) for elem in content_elements)
                    break
            
            # If no main content found, use all paragraph text
            if not main_content or len(main_content) < 100:
                paragraphs = soup.find_all('p')
                main_content = "\n".join(p.get_text(separator="\n", strip=True) for p in paragraphs)
            
            # If still no substantial content, get all text
            if not main_content or len(main_content) < 100:
                main_content = soup.get_text(separator="\n", strip=True)
            
            # Clean up text
            main_content = re.sub(r'\n+', '\n', main_content)
            
            # Extract metadata if available
            metadata = {}
            meta_tags = soup.find_all('meta')
            for tag in meta_tags:
                # Get description and keywords
                if tag.get('name') == 'description' and tag.get('content'):
                    metadata['description'] = tag.get('content')
                elif tag.get('name') == 'keywords' and tag.get('content'):
                    metadata['keywords'] = tag.get('content')
            
            # Construct the result
            result = f"Title: {title}\nURL: {url}\n"
            
            if metadata:
                if 'description' in metadata:
                    result += f"\nDescription: {metadata['description']}\n"
                if 'keywords' in metadata:
                    result += f"\nKeywords: {metadata['keywords']}\n"
            
            result += "\nContent:\n"
            
            # Limit text length, keeping proportion from beginning and end
            if len(main_content) > 10000:
                # Take first 70% from the beginning and 30% from the end
                beginning_len = int(10000 * 0.7)
                ending_len = 10000 - beginning_len
                
                result += main_content[:beginning_len] + "\n\n[...Content truncated...]\n\n" + main_content[-ending_len:]
                result += "\n\n[Content truncated due to length]"
            else:
                result += main_content
            
            return result
            
        except Exception as e:
            logger.error(f"Error accessing {url}: {str(e)}", exc_info=True)
            return f"Error accessing {url}: {str(e)}"

# Test code
if __name__ == "__main__":
    # Configure logging for testing
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    search_tool = EnhancedWebSearchTool()
    
    # Test basic search
    query = "Who won the Nobel Prize in Physics in 2023"
    print(f"\nSearching for: {query}")
    results = search_tool.search(query)
    print(results)
    
    # Test multi-engine search
    print("\nTesting multi-engine search...")
    combined_results = search_tool.search_with_all_engines(query, max_results=2)
    print("\n" + combined_results)
    
    # Test webpage browsing
    url = "https://en.wikipedia.org/wiki/Nobel_Prize_in_Physics"
    print(f"\nBrowsing webpage: {url}")
    content = search_tool.browse_webpage(url)
    print("\nWebpage content preview:")
    print(content[:500] + "...")