File size: 45,797 Bytes
8850406
 
 
 
 
 
 
 
 
 
 
 
 
 
f7af463
8850406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc6bf99
 
 
 
8850406
 
fc6bf99
8850406
 
 
 
 
 
 
 
 
fc6bf99
8850406
 
 
 
 
 
 
 
fc6bf99
8850406
fc6bf99
 
8850406
fc6bf99
 
8850406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7af463
8850406
fc6bf99
 
8850406
fc6bf99
8850406
fcd8049
 
 
 
fc6bf99
fcd8049
 
 
 
fc6bf99
fcd8049
f7af463
 
 
 
 
fcd8049
f7af463
2ad9a80
fc6bf99
 
 
 
 
 
 
f7af463
 
 
fcd8049
f7af463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc6bf99
 
 
 
 
 
8850406
fc6bf99
 
 
 
8850406
f7af463
 
 
 
 
 
 
 
8850406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2e30e2
 
8850406
 
fc6bf99
 
 
 
 
 
 
 
 
 
 
9df58dd
 
 
 
 
 
fc6bf99
 
9df58dd
 
 
 
 
 
 
 
fc6bf99
 
8850406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2e30e2
 
8850406
 
fc6bf99
 
 
 
 
 
 
 
 
 
 
9df58dd
 
 
 
 
 
fc6bf99
 
9df58dd
 
 
 
 
 
 
 
fc6bf99
 
8850406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
"""
Evolusis AI Agent - Unified Single Application
All-in-one Streamlit app with integrated AI agent logic

Run with: streamlit run app.py
"""

import streamlit as st
import os
import time
import logging
import json
import re
import copy
import tempfile
from datetime import datetime
from typing import Optional, Dict, Any, List
from collections import deque
import requests
from dotenv import load_dotenv
from groq import Groq

# Load environment variables
load_dotenv()

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Environment variables
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")
NEWS_API_KEY = os.getenv("NEWS_API_KEY")

# Initialize Groq
groq_client = None
logger.info("=== Initializing Groq Client ===")
logger.info(f"GROQ_API_KEY present: {bool(GROQ_API_KEY)}")
logger.info(f"GROQ_API_KEY length: {len(GROQ_API_KEY) if GROQ_API_KEY else 0}")

if GROQ_API_KEY:
    try:
        logger.info("Starting Groq client initialization...")
        # Initialize Groq client for HF Spaces compatibility
        # Remove any proxy-related environment variables that might interfere
        env_backup = {}
        proxy_vars = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy',
                      'ALL_PROXY', 'all_proxy', 'NO_PROXY', 'no_proxy']

        for var in proxy_vars:
            if var in os.environ:
                env_backup[var] = os.environ.pop(var)
                logger.info(f"Removed proxy variable: {var}")

        # Initialize Groq with minimal parameters
        groq_client = Groq(api_key=GROQ_API_KEY)

        # Restore environment variables
        for var, value in env_backup.items():
            os.environ[var] = value

        logger.info("βœ… Groq client initialized successfully")
    except Exception as e:
        logger.error(f"❌ Failed to initialize Groq: {type(e).__name__}: {e}")
        logger.error("Full error details:", exc_info=True)
        groq_client = None
else:
    logger.error("❌ GROQ_API_KEY not found in environment variables")

# Memory Store
class MemoryStore:
    def __init__(self, max_size=10):
        self.sessions = {}
        self.max_size = max_size
    
    def add(self, session_id: str, query: str, response: str):
        if session_id not in self.sessions:
            self.sessions[session_id] = deque(maxlen=self.max_size)
        self.sessions[session_id].append({
            "query": query,
            "response": response,
            "timestamp": datetime.now().isoformat()
        })
    
    def get_history(self, session_id: str, limit: int = 5) -> List[Dict]:
        if session_id not in self.sessions:
            return []
        return list(self.sessions[session_id])[-limit:]

memory_store = MemoryStore()

# Tool Registry
class ToolRegistry:
    @staticmethod
    def transcribe_audio(audio_file) -> Optional[str]:
        """Transcribe audio using Whisper Large V3 Turbo"""
        temp_file_path = None
        try:
            logger.info("=== Starting audio transcription ===")

            if not groq_client:
                logger.error("Groq client not initialized")
                return None

            # Ensure file pointer is at the beginning
            if hasattr(audio_file, 'seek'):
                audio_file.seek(0)
                logger.info("Reset file pointer to beginning")

            # Get the original filename or create a default one with proper extension
            # Streamlit's audio_input typically records in WAV format
            filename = getattr(audio_file, 'name', 'audio.wav')
            logger.info(f"Original filename: {filename}")

            # Determine file extension
            file_ext = '.wav'
            if any(filename.lower().endswith(ext) for ext in ['.wav', '.mp3', '.webm', '.m4a', '.ogg']):
                file_ext = os.path.splitext(filename)[1]
            logger.info(f"Using file extension: {file_ext}")

            # Read the file contents
            file_contents = audio_file.read()
            file_size = len(file_contents)
            logger.info(f"Read {file_size} bytes from audio file")

            if file_size == 0:
                logger.error("Audio file is empty (0 bytes)")
                return None

            # Check if file is too small
            if file_size < 1000:
                logger.warning(f"Audio file very small: {file_size} bytes. May be too short.")

            # Save to temporary file (more reliable approach)
            with tempfile.NamedTemporaryFile(mode='wb', suffix=file_ext, delete=False) as temp_file:
                temp_file.write(file_contents)
                temp_file_path = temp_file.name
                logger.info(f"Saved audio to temporary file: {temp_file_path}")

            # Open the temporary file and send to Groq API
            logger.info(f"Sending to Groq API - Model: whisper-large-v3-turbo, Size: {file_size} bytes")

            with open(temp_file_path, 'rb') as audio_file_handle:
                try:
                    transcription = groq_client.audio.transcriptions.create(
                        file=(os.path.basename(temp_file_path), audio_file_handle.read()),
                        model="whisper-large-v3-turbo",
                        response_format="text",
                        temperature=0.0
                    )
                    logger.info("API call completed successfully")
                except Exception as api_error:
                    logger.error(f"Groq API call failed: {type(api_error).__name__}")
                    logger.error(f"API error details: {str(api_error)}")

                    # Try to extract more details if it's a Groq API error
                    if hasattr(api_error, 'response'):
                        logger.error(f"Response status: {getattr(api_error.response, 'status_code', 'N/A')}")
                        logger.error(f"Response body: {getattr(api_error.response, 'text', 'N/A')}")

                    raise  # Re-raise to be caught by outer exception handler

            result = str(transcription)
            logger.info(f"Transcription successful. Length: {len(result)} characters")
            logger.info(f"Transcription preview: {result[:100]}...")
            return result

        except Exception as e:
            logger.error(f"=== Whisper API Error ===")
            logger.error(f"Error type: {type(e).__name__}")
            logger.error(f"Error message: {str(e)}")
            logger.error(f"Full error details:", exc_info=True)
            return None
        finally:
            # Clean up temporary file
            if temp_file_path and os.path.exists(temp_file_path):
                try:
                    os.unlink(temp_file_path)
                    logger.info(f"Cleaned up temporary file: {temp_file_path}")
                except Exception as cleanup_error:
                    logger.warning(f"Failed to cleanup temp file: {cleanup_error}")
    
    @staticmethod
    def get_weather(city: str) -> Optional[Dict[str, Any]]:
        try:
            if not OPENWEATHER_API_KEY:
                return None
            url = f"http://api.openweathermap.org/data/2.5/weather"
            params = {"q": city, "appid": OPENWEATHER_API_KEY, "units": "metric"}
            response = requests.get(url, params=params, timeout=5)
            response.raise_for_status()
            data = response.json()
            return {
                "temperature": data["main"]["temp"],
                "description": data["weather"][0]["description"],
                "humidity": data["main"]["humidity"],
                "city": data["name"],
                "country": data["sys"]["country"]
            }
        except Exception as e:
            logger.error(f"Weather API error: {e}")
            return None
    
    @staticmethod
    def get_wikipedia(topic: str) -> Optional[str]:
        try:
            url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + topic.replace(" ", "_")
            response = requests.get(url, timeout=5)
            response.raise_for_status()
            return response.json().get("extract", "No information found")
        except Exception as e:
            logger.error(f"Wikipedia API error: {e}")
            return None
    
    @staticmethod
    def get_news(query: str) -> Optional[List[Dict]]:
        try:
            if not NEWS_API_KEY:
                return None
            url = "https://newsapi.org/v2/everything"
            params = {"q": query, "apiKey": NEWS_API_KEY, "pageSize": 3, "sortBy": "publishedAt", "language": "en"}
            response = requests.get(url, params=params, timeout=5)
            response.raise_for_status()
            data = response.json()
            if data.get("articles"):
                return [{"title": a["title"], "description": a.get("description", ""), 
                        "source": a["source"]["name"], "url": a["url"]} for a in data["articles"][:3]]
            return None
        except Exception as e:
            logger.error(f"News API error: {e}")
            return None

# AI Agent
class AIAgent:
    def __init__(self):
        self.tools = ToolRegistry()
    
    def decide_tool(self, query: str, history: Optional[List[Dict]] = None) -> Dict[str, Any]:
        """Use LLM reasoning to decide which tools to use"""
        if not groq_client:
            # Fallback to simple pattern matching if LLM not available
            return self._fallback_decision(query, history)

        llm_decision = ""  # Initialize to avoid unbound variable error
        try:
            # Build rich context from history
            context_str = "No previous conversation."
            if history and len(history) > 0:
                context_parts = []
                for h in history[-3:]:
                    q = h.get('query', '')
                    r = h.get('response', '')[:150]  # Truncate response
                    context_parts.append(f"User: {q}\nAssistant: {r}")
                context_str = "\n\n".join(context_parts)

            # Create enhanced reasoning prompt
            reasoning_prompt = f"""You are an intelligent tool routing system that analyzes user queries to determine which external tools to invoke.

**Available Tools:**
1. **WEATHER** - Fetch current weather data for any city/location/country
   - Use when: User mentions weather, temperature, climate, or location names (cities, countries, regions)
   - Examples: "weather in Paris", "how's the climate in Tokyo", "america?" (after weather context), "London temperature"
   - Can extract location from: explicit mentions, country names, city names, or follow-up questions

2. **WIKIPEDIA** - Retrieve factual knowledge about people, places, events, concepts
   - Use when: User asks "who is", "what is", "tell me about", "explain", historical/biographical queries
   - Examples: "who invented the telephone", "what is quantum physics", "Albert Einstein"

3. **NEWS** - Get latest news articles on specific topics
   - Use when: User asks about "news", "latest", "recent events", "headlines", current happenings
   - Examples: "latest AI news", "what's happening in tech", "recent developments"

4. **LLM_ONLY** - Use language model for general conversation, reasoning, explanations
   - Use when: No external data needed, creative/opinion questions, general chat

**Recent Conversation Context:**
{context_str}

**Current Query:** {query}

**Analysis Instructions:**
- If query is very short (1-2 words) like "america?", "paris", "london" - check conversation history
- If previous query was about weather, treat short location names as weather requests
- Country names (USA, America, India, France, etc.) should trigger WEATHER when appropriate
- Ambiguous queries should prefer external data sources over LLM-only responses
- Use conversation context to resolve ambiguity in follow-up questions

**Response Format (JSON only):**
{{
  "use_weather": true/false,
  "use_wikipedia": true/false,
  "use_news": true/false,
  "city": "city/country/location name if weather needed, else null",
  "topic": "topic name if wikipedia needed, else null",
  "news_query": "search terms if news needed, else null",
  "reasoning": "Clear explanation: What did you detect? Why these tools? What context influenced your decision?"
}}

**Important:**
- For location queries (cities, countries, regions), always prefer WEATHER tool
- "America" / "USA" should be treated as weather query if context suggests it
- Be smart about follow-up questions - use conversation history
- Provide detailed reasoning explaining your tool selection logic"""

            response = groq_client.chat.completions.create(
                model="llama-3.3-70b-versatile",
                messages=[
                    {"role": "system", "content": "You are an expert tool routing system. Analyze queries deeply and respond with valid JSON only. No markdown, no explanations outside JSON."},
                    {"role": "user", "content": reasoning_prompt}
                ],
                temperature=0.2,
                max_tokens=400
            )

            # Parse LLM response
            llm_decision = response.choices[0].message.content
            if not llm_decision:
                logger.warning("Empty LLM response, using fallback")
                return self._fallback_decision(query, history)

            # Extract JSON from response (handle potential markdown formatting)
            json_match = re.search(r'\{[\s\S]*\}', llm_decision)
            if json_match:
                decision_data = json.loads(json_match.group())
            else:
                decision_data = json.loads(llm_decision)

            # Build decision object
            decision = {
                "use_weather": decision_data.get("use_weather", False),
                "use_wikipedia": decision_data.get("use_wikipedia", False),
                "use_news": decision_data.get("use_news", False),
                "use_llm": True,
                "extracted_params": {},
                "reasoning": decision_data.get("reasoning", "LLM tool routing decision made")
            }

            # Extract parameters with validation
            if decision["use_weather"]:
                city = decision_data.get("city")
                if city and city != "null":
                    decision["extracted_params"]["city"] = city
                    logger.info(f"Weather tool selected for city: {city}")
                else:
                    logger.warning("Weather tool selected but no city extracted")
                    decision["use_weather"] = False
            
            if decision["use_wikipedia"]:
                topic = decision_data.get("topic")
                if topic and topic != "null":
                    decision["extracted_params"]["topic"] = topic
                    logger.info(f"Wikipedia tool selected for topic: {topic}")
            
            if decision["use_news"]:
                news_query = decision_data.get("news_query")
                if news_query and news_query != "null":
                    decision["extracted_params"]["news_query"] = news_query
                    logger.info(f"News tool selected for query: {news_query}")

            return decision

        except json.JSONDecodeError as e:
            logger.error(f"JSON parsing error in LLM response: {e}")
            if 'llm_decision' in locals():
                logger.error(f"LLM response was: {llm_decision}")
            return self._fallback_decision(query, history)
        except Exception as e:
            logger.error(f"LLM reasoning error: {e}")
            # Fallback to pattern matching
            return self._fallback_decision(query, history)

    def _fallback_decision(self, query: str, history: Optional[List[Dict]] = None) -> Dict[str, Any]:
        """Enhanced fallback pattern-based decision making with better context awareness"""
        query_lower = query.lower().strip()
        decision = {
            "use_weather": False, 
            "use_wikipedia": False, 
            "use_news": False, 
            "use_llm": True, 
            "extracted_params": {}, 
            "reasoning": "Pattern-based routing (LLM unavailable)"
        }

        # Analyze conversation history for context
        previous_context = ""
        was_weather_context = False
        was_wiki_context = False
        
        if history and len(history) > 0:
            last_query = history[-1].get("query", "").lower()
            previous_context = last_query
            
            # Check what the last query was about
            weather_keywords = ["weather", "temperature", "forecast", "climate", "hot", "cold", "rain", "sunny", "cloudy"]
            was_weather_context = any(kw in previous_context for kw in weather_keywords)
            
            wiki_keywords = ["who is", "what is", "tell me about", "explain"]
            was_wiki_context = any(kw in previous_context for kw in wiki_keywords)

        # Extract potential location/topic from query
        query_words = query_lower.strip("?,.! ").split()
        
        # WEATHER DETECTION
        weather_keywords = ["weather", "temperature", "forecast", "climate", "hot", "cold", "rain", "sunny", "cloudy"]
        has_weather_keyword = any(kw in query_lower for kw in weather_keywords)
        
        # Countries and major locations that should trigger weather
        location_names = [
            "america", "usa", "united states", "india", "china", "japan", "france", "germany", 
            "london", "paris", "tokyo", "mumbai", "delhi", "bangalore", "new york", "sydney",
            "chembur", "andheri", "bandra", "pune", "hyderabad", "chennai", "kolkata",
            "california", "texas", "florida", "europe", "asia", "africa"
        ]
        has_location = any(loc in query_lower for loc in location_names)
        
        # Short query after weather context = likely a location follow-up
        is_short_followup = len(query_words) <= 2 and was_weather_context
        
        # Decide if this is a weather query
        if has_weather_keyword or has_location or is_short_followup:
            decision["use_weather"] = True
            city = self._extract_city(query, previous_context)
            if city:
                decision["extracted_params"]["city"] = city
                decision["reasoning"] = f"Detected weather query for location: {city}"
            else:
                # If no city extracted, disable weather tool
                decision["use_weather"] = False

        # WIKIPEDIA DETECTION
        knowledge_keywords = ["who is", "what is", "tell me about", "explain", "who invented", "who discovered", "define"]
        if any(kw in query_lower for kw in knowledge_keywords):
            decision["use_wikipedia"] = True
            topic = self._extract_topic(query)
            decision["extracted_params"]["topic"] = topic
            decision["reasoning"] = f"Knowledge query detected for: {topic}"

        # NEWS DETECTION
        news_keywords = ["news", "latest", "recent", "happening", "current events", "headlines", "breaking"]
        if any(kw in query_lower for kw in news_keywords):
            decision["use_news"] = True
            news_query = self._extract_news_query(query)
            decision["extracted_params"]["news_query"] = news_query
            decision["reasoning"] = f"News query detected for: {news_query}"

        return decision
    
    def _extract_city(self, query: str, previous_context: str = "") -> Optional[str]:
        """Enhanced city extraction with country/region support"""
        query_lower = query.lower().strip()
        
        # Handle explicit "in" syntax: "weather in Paris"
        if " in " in query_lower:
            parts = query_lower.split(" in ")
            if len(parts) > 1:
                city_part = parts[1].strip("?,.! ").split()[0]
                return city_part.title()

        # Map country/region names to capitals or major cities for weather API
        country_to_city = {
            "america": "New York",
            "usa": "New York",
            "united states": "New York",
            "india": "Mumbai",
            "china": "Beijing",
            "japan": "Tokyo",
            "france": "Paris",
            "germany": "Berlin",
            "uk": "London",
            "united kingdom": "London",
            "australia": "Sydney",
            "canada": "Toronto",
            "brazil": "Rio de Janeiro",
            "russia": "Moscow",
            "italy": "Rome",
            "spain": "Madrid",
            "mexico": "Mexico City"
        }
        
        # Check for country names
        for country, city in country_to_city.items():
            if country in query_lower:
                logger.info(f"Mapped country '{country}' to city '{city}'")
                return city

        # Common cities and locations
        cities = [
            "london", "paris", "tokyo", "new york", "mumbai", "delhi", "bangalore", "sydney",
            "chembur", "andheri", "bandra", "pune", "hyderabad", "chennai", "kolkata",
            "berlin", "madrid", "rome", "beijing", "shanghai", "los angeles", "chicago",
            "toronto", "vancouver", "dubai", "singapore", "hong kong", "seoul"
        ]
        
        for city in cities:
            if city in query_lower:
                return city.title()

        # If query is very short (1-2 words) and looks like a location name, use it
        words = query.strip("?,. ").split()
        if len(words) <= 2:
            potential_city = query.strip("?,. ").title()
            # Additional validation: if all letters (no special chars), likely a location
            if potential_city.replace(" ", "").isalpha():
                logger.info(f"Treating short query '{potential_city}' as location name")
                return potential_city

        return None
    
    def _extract_topic(self, query: str) -> str:
        stop_words = ["who is", "what is", "tell me about", "explain", "who invented", "who discovered", "what's", "the"]
        topic = query.lower()
        for word in stop_words:
            topic = topic.replace(word, "")
        return topic.strip("?,. ")
    
    def _extract_news_query(self, query: str) -> str:
        stop_words = ["news", "latest", "recent", "what's", "tell me", "about", "the"]
        topic = query.lower()
        for word in stop_words:
            topic = topic.replace(word, "")
        return topic.strip("?,. ") or "technology"
    
    def process_query(self, query: str, session_id: str) -> dict:
        start_time = time.time()
        tools_used = []
        reasoning_parts = []
        
        history = memory_store.get_history(session_id, limit=3)
        decision = self.decide_tool(query, history)

        # Add LLM reasoning if available
        if decision.get("reasoning"):
            reasoning_parts.append(f"🧠 LLM Decision: {decision['reasoning']}")
        else:
            reasoning_parts.append(f"Analyzed query intent: {query}")
        
        external_data = []
        
        if decision["use_weather"]:
            city = decision["extracted_params"].get("city")
            if city:
                reasoning_parts.append(f"Fetching weather for {city}")
                weather = self.tools.get_weather(city)
                if weather:
                    tools_used.append("OpenWeather API")
                    external_data.append(f"Weather in {weather['city']}, {weather['country']}: {weather['temperature']}Β°C, {weather['description']}, Humidity: {weather['humidity']}%")
        
        if decision["use_news"]:
            news_query = decision["extracted_params"].get("news_query", "technology")
            reasoning_parts.append(f"Fetching news about {news_query}")
            news = self.tools.get_news(news_query)
            if news:
                tools_used.append("NewsAPI")
                news_text = "\n".join([f"- {item['title']} ({item['source']})" for item in news])
                external_data.append(f"Latest news:\n{news_text}")
        
        if decision["use_wikipedia"]:
            topic = decision["extracted_params"].get("topic")
            if topic:
                reasoning_parts.append(f"Fetching Wikipedia info for {topic}")
                wiki_data = self.tools.get_wikipedia(topic)
                if wiki_data:
                    tools_used.append("Wikipedia API")
                    external_data.append(f"Wikipedia: {wiki_data[:500]}")
                else:
                    reasoning_parts.append("Wikipedia data not available")
        
        reasoning_parts.append("Generating response with GPT oss-120B")
        
        if groq_client:
            tools_used.append("GPT oss-120B (Groq)")
            llm_response = self._call_groq(query, external_data, history)
        else:
            llm_response = "AI model unavailable. Please configure GROQ_API_KEY."
        
        memory_store.add(session_id, query, llm_response)
        response_time = int((time.time() - start_time) * 1000)
        
        return {
            "reasoning": " β†’ ".join(reasoning_parts),
            "answer": llm_response,
            "tools_used": tools_used,
            "response_time_ms": response_time,
            "session_id": session_id
        }
    
    def _call_groq(self, query: str, external_data: List[str], history: List[Dict]) -> str:
        if not groq_client:
            return "Groq client not initialized. Please check GROQ_API_KEY."
        
        try:
            prompt_parts = ["You are a helpful AI assistant."]
            if history:
                prompt_parts.append("\nHistory:")
                for item in history:
                    prompt_parts.append(f"User: {item['query']}\nAssistant: {item['response'][:200]}...")
            if external_data:
                prompt_parts.append("\nExternal Data:")
                prompt_parts.extend(external_data)
            prompt_parts.append(f"\nUser: {query}\nProvide a helpful response:")
            
            response = groq_client.chat.completions.create(
                model="llama-3.3-70b-versatile",
                messages=[{"role": "system", "content": "You are a helpful AI assistant."},
                         {"role": "user", "content": "\n".join(prompt_parts)}],
                temperature=0.7,
                max_tokens=500
            )
            return response.choices[0].message.content or "No response generated."
        except Exception as e:
            logger.error(f"Groq error: {e}")
            return "Error generating response."

# Initialize agent
agent = AIAgent()

# Streamlit UI starts here
if True:
    # Page configuration
    st.set_page_config(
        page_title="Evolusis AI Agent",
        page_icon="πŸ€–",
        layout="wide",
        initial_sidebar_state="expanded"
    )
    
    # Custom CSS
    st.markdown("""
    <style>
        .main {
            background-color: #0e1117;
        }
        .stTextInput > div > div > input {
            background-color: #1e1e1e;
            color: #ffffff;
            border: 1px solid #333;
            border-radius: 8px;
            padding: 12px;
        }
        .user-message {
            background-color: #2b5278;
            color: white;
            padding: 12px 16px;
            border-radius: 12px;
            margin: 8px 0;
            margin-left: 20%;
            text-align: right;
        }
        .assistant-message {
            background-color: #1e1e1e;
            color: #e0e0e0;
            padding: 12px 16px;
            border-radius: 12px;
            margin: 8px 0;
            margin-right: 20%;
        }
        .metadata {
            font-size: 0.8em;
            color: #888;
            margin-top: 6px;
        }
        .tool-badge {
            display: inline-block;
            background-color: #333;
            color: #4CAF50;
            padding: 2px 8px;
            border-radius: 4px;
            margin-right: 6px;
            font-size: 0.75em;
        }
        .welcome-section {
            text-align: center;
            padding: 5px 20px;
        }
        .dev-info-card {
            text-align: center;
            padding: 5px;
            margin: 10px 0;
            color: #e0e0e0;
            font-size: 0.95em;
        }
        .dev-info-card a {
            color: #60a5fa;
            text-decoration: none;
        }
        .dev-info-card a:hover {
            text-decoration: underline;
        }
        .status-bar {
            padding: 8px 20px;
            margin-top: 30px;
            text-align: center;
            color: #888;
            font-size: 0.85em;
        }
        h1 {
            color: #4CAF50;
        }
        /* Sidebar conversation history - plain text style */
        .stSidebar button[kind="secondary"] {
            background: transparent !important;
            border: none !important;
            box-shadow: none !important;
            padding: 4px 0 !important;
            text-align: left !important;
            color: #e0e0e0 !important;
            font-size: 0.9em !important;
        }
        .stSidebar button[kind="secondary"]:hover {
            background: transparent !important;
            color: #60a5fa !important;
        }
    </style>
    """, unsafe_allow_html=True)
    
    # Initialize session state
    if "messages" not in st.session_state:
        st.session_state.messages = []
    if "session_id" not in st.session_state:
        st.session_state.session_id = f"session_{int(time.time())}_{hash(time.time())}"
    if "chat_history" not in st.session_state:
        st.session_state.chat_history = []
    if "saved_conversations" not in st.session_state:
        st.session_state.saved_conversations = []
    if "processing" not in st.session_state:
        st.session_state.processing = False
    if "last_input" not in st.session_state:
        st.session_state.last_input = ""
    
    # Example queries
    EXAMPLE_QUERIES = [
        "What's the weather in Paris today?",
        "Who invented the telephone?",
        "Latest news about artificial intelligence",
        "Tell me about Albert Einstein",
        "Weather in Mumbai",
        "Recent technology news",
        "What is quantum computing?",
        "Explain the theory of relativity",
        "What are the benefits of meditation?",
        "How does photosynthesis work?"
    ]
    
    def call_agent(query: str) -> dict:
        """Call the AI agent directly"""
        try:
            return agent.process_query(query, st.session_state.session_id)
        except Exception as e:
            logger.error(f"Agent error: {e}")
            return {
                "answer": f"❌ Error: {str(e)}",
                "tools_used": [],
                "response_time_ms": 0,
                "reasoning": f"Error: {str(e)}"
            }
    
    def display_message(message: dict):
        """Display a chat message"""
        if message["role"] == "user":
            st.markdown(f'<div class="user-message">πŸ‘€ {message["content"]}</div>', unsafe_allow_html=True)
        else:
            # Show reasoning in collapsible section
            if "reasoning" in message and message["reasoning"]:
                with st.expander("🧠 Reasoning", expanded=False):
                    st.markdown("**Decision Process:**")
                    st.text(message["reasoning"])
                    
                    # Show JSON response
                    st.markdown("**JSON Response:**")
                    json_output = {
                        "reasoning": message["reasoning"],
                        "answer": message["content"],
                        "tools_used": message.get("tools_used", []),
                        "response_time_ms": message.get("response_time_ms", 0),
                        "timestamp": message.get("timestamp", "")
                    }
                    st.json(json_output)
            
            # Show main answer
            st.markdown(f'<div class="assistant-message">πŸ€– {message["content"]}</div>', unsafe_allow_html=True)
            
            if "tools_used" in message and message["tools_used"]:
                tools_html = " ".join([f'<span class="tool-badge">{tool}</span>' for tool in message["tools_used"]])
                metadata = f'<div class="metadata">{tools_html}'
                if "response_time_ms" in message and message["response_time_ms"] > 0:
                    metadata += f' ⏱️ {message["response_time_ms"]}ms'
                metadata += '</div>'
                st.markdown(metadata, unsafe_allow_html=True)
    
    def process_query(query: str):
        """Process user query"""
        # Prevent processing if already processing
        if st.session_state.processing:
            return

        st.session_state.processing = True

        st.session_state.messages.append({
            "role": "user",
            "content": query,
            "timestamp": datetime.now().isoformat()
        })

        with st.spinner("πŸ€” Thinking..."):
            response = call_agent(query)

        st.session_state.messages.append({
            "role": "assistant",
            "content": response.get("answer", "No response"),
            "tools_used": response.get("tools_used", []),
            "response_time_ms": response.get("response_time_ms", 0),
            "reasoning": response.get("reasoning", ""),
            "timestamp": datetime.now().isoformat()
        })

        # Save to chat history
        if len(st.session_state.messages) >= 2:
            st.session_state.chat_history.append({
                "query": query,
                "timestamp": datetime.now().strftime("%H:%M:%S"),
                "session_id": st.session_state.session_id
            })
            if len(st.session_state.chat_history) > 20:
                st.session_state.chat_history = st.session_state.chat_history[-20:]

        # Reset processing flag after a short delay
        st.session_state.processing = False
    
    # Header
    st.title("πŸ€– Evolusis AI Agent")
    
    # Main content
    if len(st.session_state.messages) == 0:
        # Developer info card - right after title
        st.markdown("""
        <div class="dev-info-card">
            Yash Gori - +91 7718081766 / <a href="mailto:[email protected]">Email</a> / <a href="https://yashgori20.vercel.app/" target="_blank">Portfolio</a>
        </div>
        """, unsafe_allow_html=True)
        
        # Welcome screen with developer info and status
        st.markdown('<div class="welcome-section">', unsafe_allow_html=True)
        st.markdown("### Intelligent assistant combining LLM reasoning with real-time data")
        st.markdown("**Powered by:** GPT oss-120B β€’ Whisper Large V3 Turbo β€’ OpenWeather β€’ Wikipedia β€’ NewsAPI")
        st.markdown('</div>', unsafe_allow_html=True)
        
        # Chat input and audio upload
        st.markdown("---")
        
        # Audio recording for speech-to-text
        audio_input = st.audio_input("🎀 Click to speak")
        if audio_input:
            with st.spinner("🎧 Transcribing your voice..."):
                try:
                    logger.info(f"Received audio input: {audio_input}")
                    logger.info(f"Audio input type: {type(audio_input)}")
                    logger.info(f"Audio input name: {getattr(audio_input, 'name', 'N/A')}")

                    transcription = agent.tools.transcribe_audio(audio_input)
                    if transcription:
                        st.success(f"βœ… You said: {transcription}")
                        process_query(transcription)
                        st.rerun()
                    else:
                        error_details = "Transcription returned None. Possible causes:\n"
                        error_details += "- Audio file is empty or too short\n"
                        error_details += "- Groq API key invalid or missing\n"
                        error_details += "- Network connectivity issue\n"
                        error_details += f"- Groq client initialized: {bool(groq_client)}"
                        st.error(f"❌ Transcription failed\n\n{error_details}")
                        logger.error("Transcription returned None")
                except Exception as e:
                    error_msg = f"❌ Error during transcription\n\n"
                    error_msg += f"**Error Type:** {type(e).__name__}\n\n"
                    error_msg += f"**Error Message:** {str(e)}\n\n"

                    # Add more context if available
                    if hasattr(e, '__cause__') and e.__cause__:
                        error_msg += f"**Cause:** {str(e.__cause__)}\n\n"

                    st.error(error_msg)
                    logger.error(f"Transcription UI error: {e}", exc_info=True)
        
        # Text input
        user_input = st.text_input("⌨️ Or type your question...", key="chat_input_text")
        if user_input and user_input != st.session_state.last_input:
            st.session_state.last_input = user_input
            process_query(user_input)
            st.rerun()
        
        st.markdown("---")
            
        st.markdown("🌀️ **Weather Queries:**")
        col_a, col_b = st.columns(2)
        with col_a:
            if st.button(EXAMPLE_QUERIES[0], key="ex_0", use_container_width=True):
                st.session_state.last_input = EXAMPLE_QUERIES[0]
                process_query(EXAMPLE_QUERIES[0])
                st.rerun()
        with col_b:
            if st.button(EXAMPLE_QUERIES[4], key="ex_4", use_container_width=True):
                st.session_state.last_input = EXAMPLE_QUERIES[4]
                process_query(EXAMPLE_QUERIES[4])
                st.rerun()
        
        st.markdown("πŸ“š **Knowledge Queries:**")
        col_c, col_d = st.columns(2)
        with col_c:
            if st.button(EXAMPLE_QUERIES[1], key="ex_1", use_container_width=True):
                st.session_state.last_input = EXAMPLE_QUERIES[1]
                process_query(EXAMPLE_QUERIES[1])
                st.rerun()
        with col_d:
            if st.button(EXAMPLE_QUERIES[3], key="ex_3", use_container_width=True):
                st.session_state.last_input = EXAMPLE_QUERIES[3]
                process_query(EXAMPLE_QUERIES[3])
                st.rerun()

        st.markdown("πŸ“° **News Queries:**")
        col_e, col_f = st.columns(2)
        with col_e:
            if st.button(EXAMPLE_QUERIES[2], key="ex_2", use_container_width=True):
                st.session_state.last_input = EXAMPLE_QUERIES[2]
                process_query(EXAMPLE_QUERIES[2])
                st.rerun()
        with col_f:
            if st.button(EXAMPLE_QUERIES[5], key="ex_5", use_container_width=True):
                st.session_state.last_input = EXAMPLE_QUERIES[5]
                process_query(EXAMPLE_QUERIES[5])
                st.rerun()

        st.markdown("🧠 **Reasoning Queries (Groq LLM Only):**")
        col_g, col_h = st.columns(2)
        with col_g:
            if st.button(EXAMPLE_QUERIES[6], key="ex_6", use_container_width=True):
                st.session_state.last_input = EXAMPLE_QUERIES[6]
                process_query(EXAMPLE_QUERIES[6])
                st.rerun()
            if st.button(EXAMPLE_QUERIES[8], key="ex_8", use_container_width=True):
                st.session_state.last_input = EXAMPLE_QUERIES[8]
                process_query(EXAMPLE_QUERIES[8])
                st.rerun()
        with col_h:
            if st.button(EXAMPLE_QUERIES[7], key="ex_7", use_container_width=True):
                st.session_state.last_input = EXAMPLE_QUERIES[7]
                process_query(EXAMPLE_QUERIES[7])
                st.rerun()
            if st.button(EXAMPLE_QUERIES[9], key="ex_9", use_container_width=True):
                st.session_state.last_input = EXAMPLE_QUERIES[9]
                process_query(EXAMPLE_QUERIES[9])
                st.rerun()
    else:
        # Show conversation messages
        for message in st.session_state.messages:
            display_message(message)
        
        # Continue conversation input
        st.markdown("---")
        
        # Audio recording for follow-up
        audio_input = st.audio_input("🎀 Click to speak", key="followup_audio")
        if audio_input and not st.session_state.processing:
            with st.spinner("🎧 Transcribing your voice..."):
                try:
                    logger.info(f"Received followup audio input: {audio_input}")
                    logger.info(f"Audio input type: {type(audio_input)}")
                    logger.info(f"Audio input name: {getattr(audio_input, 'name', 'N/A')}")

                    transcription = agent.tools.transcribe_audio(audio_input)
                    if transcription:
                        st.success(f"βœ… You said: {transcription}")
                        process_query(transcription)
                        st.rerun()
                    else:
                        error_details = "Transcription returned None. Possible causes:\n"
                        error_details += "- Audio file is empty or too short\n"
                        error_details += "- Groq API key invalid or missing\n"
                        error_details += "- Network connectivity issue\n"
                        error_details += f"- Groq client initialized: {bool(groq_client)}"
                        st.error(f"❌ Transcription failed\n\n{error_details}")
                        logger.error("Transcription returned None")
                except Exception as e:
                    error_msg = f"❌ Error during transcription\n\n"
                    error_msg += f"**Error Type:** {type(e).__name__}\n\n"
                    error_msg += f"**Error Message:** {str(e)}\n\n"

                    # Add more context if available
                    if hasattr(e, '__cause__') and e.__cause__:
                        error_msg += f"**Cause:** {str(e.__cause__)}\n\n"

                    st.error(error_msg)
                    logger.error(f"Transcription UI error: {e}", exc_info=True)

        # Text input for follow-up
        user_input = st.text_input("⌨️ Continue the conversation...", key="followup_text")
        if user_input and user_input != st.session_state.last_input and not st.session_state.processing:
            st.session_state.last_input = user_input
            process_query(user_input)
            st.rerun()
    
    # System Status Bar at the end
    status_groq = 'βœ“' if groq_client is not None else 'βœ—'
    status_weather = 'βœ“' if OPENWEATHER_API_KEY else 'βœ—'
    status_news = 'βœ“' if NEWS_API_KEY else 'βœ—'
    
    st.markdown(f"""
    <div class="status-bar">
        Groq {status_groq} | Weather {status_weather} | News {status_news} | Wiki βœ“ | Sessions: {len(memory_store.sessions)}
    </div>
    """, unsafe_allow_html=True)
    
    # Left Sidebar - Chat History and Controls
    with st.sidebar:
        if st.button("πŸ”„ New Chat", use_container_width=True):
            # Save current conversation before starting new one
            if st.session_state.messages:
                first_query = st.session_state.messages[0]["content"] if st.session_state.messages else "Conversation"
                # Create a deep copy to avoid reference issues
                st.session_state.saved_conversations.append({
                    "title": first_query[:50] + "...",
                    "messages": copy.deepcopy(st.session_state.messages),
                    "session_id": st.session_state.session_id,  # Keep original session ID for history
                    "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M")
                })
                # Keep only last 10 conversations
                if len(st.session_state.saved_conversations) > 10:
                    st.session_state.saved_conversations = st.session_state.saved_conversations[-10:]
            
            st.session_state.messages = []
            # Generate a new session ID for the new chat
            st.session_state.session_id = f"session_{int(time.time())}_{hash(time.time())}"
            st.session_state.last_input = ""
            st.rerun()
        
        if st.button("πŸ—‘οΈ Clear History", use_container_width=True):
            st.session_state.chat_history = []
            st.session_state.saved_conversations = []
            st.rerun()
        
        st.markdown("<div style='margin: 20px 0; border-top: 1px solid #333;'></div>", unsafe_allow_html=True)
        
        if st.session_state.saved_conversations:
            for idx, conv in enumerate(reversed(st.session_state.saved_conversations)):
                # Simple clickable text without button box styling
                if st.button(conv['title'], key=f"conv_{idx}"):
                    # Restore this conversation with deep copy to avoid reference issues
                    st.session_state.messages = copy.deepcopy(conv["messages"])
                    # Generate a new session ID to avoid memory store conflicts
                    st.session_state.session_id = f"session_{int(time.time())}_{hash(time.time())}"
                    st.rerun()
                
                # Minimal separator with less padding
                if idx < len(st.session_state.saved_conversations) - 1:
                    st.markdown("<div style='margin: 4px 0; border-top: 1px solid #222;'></div>", unsafe_allow_html=True)
        else:
            st.markdown("<div style='text-align: center; color: #666; font-size: 0.85em; margin-top: 20px;'>No saved conversations</div>", unsafe_allow_html=True)