File size: 31,774 Bytes
546b9c9
569dd78
 
546b9c9
569dd78
 
 
35535b1
b96067c
 
 
 
 
 
 
35535b1
 
 
 
 
 
 
 
 
 
 
 
 
b96067c
 
 
 
 
 
 
 
 
35535b1
 
 
 
 
 
 
 
 
 
 
 
b96067c
 
 
 
 
 
35535b1
b96067c
 
35535b1
b96067c
 
 
35535b1
 
b96067c
 
35535b1
 
 
 
 
b96067c
 
 
 
 
35535b1
 
 
 
 
 
 
 
 
 
 
b96067c
 
 
 
35535b1
b96067c
 
35535b1
 
b96067c
 
 
35535b1
 
 
 
b96067c
 
 
35535b1
 
 
 
 
 
 
b96067c
 
 
35535b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b96067c
 
35535b1
b96067c
35535b1
 
 
 
 
b96067c
 
 
 
 
 
35535b1
 
 
b96067c
 
 
 
 
 
35535b1
 
 
 
 
 
 
 
b96067c
 
 
 
 
35535b1
b96067c
 
 
 
 
35535b1
b96067c
35535b1
b96067c
 
 
 
35535b1
b96067c
 
 
35535b1
b96067c
35535b1
b96067c
 
 
 
35535b1
 
 
 
b96067c
35535b1
 
b96067c
 
 
 
 
 
35535b1
 
b96067c
 
 
35535b1
b96067c
 
 
 
 
 
35535b1
 
 
b96067c
 
 
 
35535b1
b96067c
35535b1
 
 
b96067c
 
 
 
 
35535b1
 
 
 
 
b96067c
 
 
 
 
35535b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b96067c
35535b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b96067c
 
35535b1
 
 
 
 
 
 
 
 
 
b96067c
 
 
569dd78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
546b9c9
 
569dd78
 
 
 
bfbb4e6
546b9c9
 
bfbb4e6
546b9c9
 
569dd78
 
bfbb4e6
569dd78
546b9c9
 
bfbb4e6
 
 
 
 
 
546b9c9
 
bfbb4e6
 
546b9c9
bfbb4e6
569dd78
bfbb4e6
546b9c9
569dd78
546b9c9
569dd78
 
546b9c9
569dd78
 
546b9c9
569dd78
 
 
 
546b9c9
569dd78
 
 
546b9c9
569dd78
 
 
 
546b9c9
569dd78
 
 
546b9c9
569dd78
 
 
 
546b9c9
569dd78
546b9c9
569dd78
546b9c9
569dd78
 
 
b96067c
35535b1
 
 
 
 
569dd78
35535b1
 
 
 
569dd78
35535b1
546b9c9
35535b1
 
 
 
 
 
b96067c
 
 
 
 
35535b1
 
 
 
 
 
 
 
 
569dd78
b96067c
 
569dd78
 
 
 
 
 
 
35535b1
 
 
569dd78
b96067c
35535b1
 
569dd78
 
b96067c
35535b1
 
 
 
b96067c
569dd78
35535b1
 
569dd78
35535b1
569dd78
 
b96067c
35535b1
 
 
569dd78
35535b1
 
b96067c
569dd78
35535b1
 
569dd78
35535b1
b96067c
35535b1
 
 
b96067c
35535b1
 
b96067c
 
35535b1
 
b96067c
35535b1
b96067c
35535b1
 
 
569dd78
35535b1
 
569dd78
 
35535b1
 
 
 
b96067c
35535b1
b96067c
 
 
 
 
 
 
35535b1
b96067c
 
 
35535b1
 
 
 
 
 
 
 
 
 
 
b96067c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35535b1
 
 
 
 
 
 
 
 
 
546b9c9
b96067c
 
 
 
 
 
 
 
546b9c9
b96067c
 
 
 
 
 
 
 
569dd78
b96067c
 
 
35535b1
b96067c
 
 
 
 
 
 
 
 
 
 
35535b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b96067c
 
 
 
 
 
 
 
 
 
 
 
 
35535b1
 
 
 
 
 
 
 
 
 
b96067c
 
35535b1
 
 
 
 
 
 
 
 
 
b96067c
35535b1
 
 
 
 
 
 
 
 
 
 
569dd78
35535b1
 
 
 
 
b96067c
35535b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
569dd78
 
35535b1
569dd78
35535b1
 
 
 
 
 
 
b96067c
35535b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
from typing import Union, List, Dict
from groq import Groq
import os
from duckduckgo_search import DDGS

# Set page configuration with fullscreen layout and custom theme
st.set_page_config(
    page_title="Z-Agent News Analysis",
    layout="wide",
    initial_sidebar_state="collapsed",
    page_icon="πŸ”"
)

# Execute JavaScript to make the app fullscreen on load
st.markdown("""
<script>
    document.addEventListener('DOMContentLoaded', (event) => {
        // Request fullscreen on page load
        document.documentElement.requestFullscreen().catch(e => {
            console.log("Fullscreen request failed: ", e);
        });
    });
</script>
""", unsafe_allow_html=True)

# Enhanced CSS for a more beautiful Google DeepMind-inspired styling
st.markdown("""
<style>
    /* Global font and color scheme */
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
    
    html, body, [class*="css"] {
        font-family: 'Inter', sans-serif;
    }
    
    /* Background and main container styling */
    .main {
        background: linear-gradient(135deg, #f5f7fa 0%, #ebeff5 100%);
        padding: 0;
    }
    
    .main .block-container {
        padding-top: 2rem;
        padding-bottom: 3rem;
        max-width: 1300px;
    }
    
    /* Header styling */
    h1 {
        color: #101010;
        font-weight: 700 !important;
        margin-bottom: 1rem !important;
        letter-spacing: -0.5px;
        font-size: 2.8rem !important;
    }
    
    h2 {
        font-weight: 600 !important;
        color: #202020;
        letter-spacing: -0.3px;
        font-size: 1.8rem !important;
        margin-top: 1.5rem !important;
    }
    
    h3 {
        font-weight: 600 !important;
        color: #303030;
        letter-spacing: -0.2px;
        font-size: 1.4rem !important;
    }
    
    /* Card-like sections */
    .card {
        background-color: white;
        border-radius: 16px;
        padding: 2rem;
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
        margin-bottom: 2rem;
        border: 1px solid rgba(240, 240, 240, 0.9);
        transition: all 0.3s ease;
    }
    
    .card:hover {
        box-shadow: 0 12px 36px rgba(0, 0, 0, 0.12);
        transform: translateY(-3px);
    }
    
    /* Button styling */
    .stButton > button {
        background: linear-gradient(90deg, #1a73e8, #0b5cbe);
        color: white;
        border: none;
        border-radius: 8px;
        padding: 0.8rem 1.5rem;
        font-weight: 500;
        transition: all 0.3s;
        width: 100%;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        font-size: 1rem;
        box-shadow: 0 4px 12px rgba(26, 115, 232, 0.3);
    }
    
    .stButton > button:hover {
        background: linear-gradient(90deg, #1765cc, #0a51a8);
        box-shadow: 0 6px 16px rgba(26, 115, 232, 0.4);
        transform: translateY(-2px);
    }
    
    .stButton > button:active {
        transform: translateY(1px);
    }
    
    /* Input field styling */
    .stTextInput input {
        border-radius: 8px;
        border: 2px solid #E0E0E0;
        padding: 1rem;
        font-size: 1rem;
        transition: all 0.3s;
    }
    
    .stTextInput input:focus {
        border-color: #1a73e8;
        box-shadow: 0 0 0 4px rgba(26, 115, 232, 0.2);
    }
    
    .stSelectbox div[data-baseweb="select"] div {
        border-radius: 8px;
        border: 2px solid #E0E0E0;
        padding: 0.25rem;
    }
    
    .stSelectbox div[data-baseweb="select"] div:focus {
        border-color: #1a73e8;
        box-shadow: 0 0 0 4px rgba(26, 115, 232, 0.2);
    }
    
    .stSlider div[data-baseweb="slider"] {
        border-radius: 8px;
    }
    
    /* Analysis result styling */
    .analysis-result {
        background-color: #F8F9FA;
        border-radius: 12px;
        padding: 2rem;
        border-left: 6px solid #1a73e8;
        line-height: 1.7;
    }
    
    /* Expand/collapse sections */
    .streamlit-expanderHeader {
        font-weight: 500;
        color: #5f6368;
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 0.8rem !important;
        border: 1px solid #e8eaed;
    }
    
    .streamlit-expanderHeader:hover {
        background-color: #f1f3f4;
    }
    
    /* Spinner/progress styling */
    .stSpinner > div {
        border-color: #1a73e8 transparent transparent !important;
        border-width: 3px !important;
    }
    
    /* Footer styling */
    footer {
        border-top: 1px solid #F0F0F0;
        padding-top: 1.5rem;
        color: #5f6368;
        font-size: 0.9rem;
    }
    
    /* Logo and branding */
    .logo-text {
        font-weight: 700;
        background: linear-gradient(90deg, #1a73e8, #8ab4f8);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-size: 2.8rem;
        letter-spacing: -1px;
        text-shadow: 0px 4px 8px rgba(26, 115, 232, 0.2);
    }
    
    /* Sections */
    .section-header {
        font-size: 1.3rem;
        font-weight: 600;
        margin-top: 2rem;
        margin-bottom: 1.2rem;
        color: #202124;
        padding-bottom: 0.5rem;
        border-bottom: 2px solid #f1f3f4;
    }
    
    /* Source links */
    a {
        color: #1a73e8;
        text-decoration: none;
        transition: all 0.2s;
        font-weight: 500;
    }
    
    a:hover {
        color: #0b5cbe;
        text-decoration: underline;
    }
    
    /* Tabs for analysis results */
    .stTabs [data-baseweb="tab-list"] {
        gap: 2px;
        border-radius: 12px;
        background-color: #f8f9fa;
        padding: 5px;
    }
    
    .stTabs [data-baseweb="tab"] {
        background-color: transparent;
        border-radius: 8px;
        color: #5f6368;
        padding: 10px 20px;
        font-weight: 500;
        transition: all 0.2s;
    }
    
    .stTabs [aria-selected="true"] {
        background-color: white !important;
        color: #1a73e8 !important;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    .stTabs [data-baseweb="tab"]:hover:not([aria-selected="true"]) {
        background-color: rgba(0, 0, 0, 0.05);
    }
    
    /* Info boxes */
    .info-box {
        background-color: #E8F0FE;
        border-radius: 12px;
        padding: 1.2rem;
        border-left: 6px solid #1a73e8;
        margin-bottom: 1.5rem;
        box-shadow: 0 4px 12px rgba(26, 115, 232, 0.15);
    }
    
    /* Progress animation */
    @keyframes pulse {
        0% { opacity: 0.6; }
        50% { opacity: 1; }
        100% { opacity: 0.6; }
    }
    
    .pulsing {
        animation: pulse 1.5s infinite ease-in-out;
    }
    
    /* Source item styling */
    .source-item {
        margin-bottom: 1.5rem;
        padding-bottom: 1.5rem;
        border-bottom: 1px solid #f0f0f0;
        transition: all 0.3s;
    }
    
    .source-item:hover {
        background-color: #f8f9fa;
        padding: 1rem;
        margin: 0 -1rem 1.5rem -1rem;
        border-radius: 8px;
    }
    
    .source-title {
        margin-bottom: 0.3rem;
        font-weight: 600;
        color: #202124;
        font-size: 1.1rem;
    }
    
    .source-meta {
        color: #5f6368;
        margin-bottom: 0.8rem;
        font-size: 0.9rem;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .source-meta-dot {
        display: inline-block;
        width: 4px;
        height: 4px;
        background-color: #5f6368;
        border-radius: 50%;
    }
    
    .read-link {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        font-weight: 500;
        font-size: 0.9rem;
    }
    
    /* Status indicators */
    .status-badge {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 0.4rem 0.8rem;
        border-radius: 16px;
        font-size: 0.85rem;
        font-weight: 500;
    }
    
    .status-searching {
        background-color: #e8f0fe;
        color: #1a73e8;
    }
    
    .status-analyzing {
        background-color: #e6f4ea;
        color: #137333;
    }
    
    /* Header icon animation */
    @keyframes float {
        0% { transform: translateY(0px); }
        50% { transform: translateY(-10px); }
        100% { transform: translateY(0px); }
    }
    
    .float-icon {
        animation: float 3s ease-in-out infinite;
    }
    
    /* Tips section */
    .tip-item {
        display: flex;
        align-items: flex-start;
        gap: 12px;
        margin-bottom: 1rem;
    }
    
    .tip-icon {
        color: #1a73e8;
        font-size: 1.2rem;
        margin-top: 0.2rem;
    }
    
    .tip-text {
        flex: 1;
    }
</style>
""", unsafe_allow_html=True)

class DuckDuckGoSearch:
    """
    Custom DuckDuckGo search implementation with robust error handling and result processing.
    Uses the duckduckgo_search library to fetch and format news results.
    """
    def __init__(self):
        # Initialize the DuckDuckGo search session
        self.ddgs = DDGS()
    
    def __call__(self, query: str, max_results: int = 5) -> str:
        try:
            # Perform the search and get results
            # The news method is more appropriate for recent news analysis
            search_results = list(self.ddgs.news(
                query,
                max_results=max_results,
                region='wt-wt',  # Worldwide results
                safesearch='on'
            ))
            
            if not search_results:
                return "No results found. Try modifying your search query."
            
            # Format the results into a readable string
            formatted_results = []
            for idx, result in enumerate(search_results, 1):
                # Extract available fields with fallbacks for missing data
                title = result.get('title', 'No title available')
                snippet = result.get('body', result.get('snippet', 'No description available'))
                source = result.get('source', 'Unknown source')
                url = result.get('url', result.get('link', 'No link available'))
                date = result.get('date', 'Date not available')
                
                # Format each result with available information
                formatted_results.append(
                    f"{idx}. Title: {title}\n"
                    f"   Date: {date}\n"
                    f"   Source: {source}\n"
                    f"   Summary: {snippet}\n"
                    f"   URL: {url}\n"
                )
            
            return "\n".join(formatted_results)
        
        except Exception as e:
            # Provide detailed error information for debugging
            error_msg = f"Search error: {str(e)}\nTry again with a different search term or check your internet connection."
            print(f"DuckDuckGo search error: {str(e)}")  # For logging
            return error_msg

class GroqLLM:
    """
    LLM interface using Groq's LLama model.
    Handles API communication and response processing.
    """
    def __init__(self, model_name="llama-3.1-8B-Instant"):
        self.client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
        self.model_name = model_name
    
    def __call__(self, prompt: Union[str, dict, List[Dict]]) -> str:
        try:
            # Convert prompt to string if it's a complex structure
            prompt_str = str(prompt) if isinstance(prompt, (dict, list)) else prompt
            
            # Make API call to Groq
            completion = self.client.chat.completions.create(
                model=self.model_name,
                messages=[{
                    "role": "user",
                    "content": prompt_str
                }],
                temperature=0.7,
                max_tokens=1024,
                stream=False
            )
            
            return completion.choices[0].message.content if completion.choices else "Error: No response generated"
        except Exception as e:
            error_msg = f"Error generating response: {str(e)}"
            print(error_msg)  # For logging
            return error_msg

def create_analysis_prompt(topic: str, search_results: str) -> str:
    """
    Creates a detailed prompt for news analysis, structuring the request
    to get comprehensive and well-organized results from the LLM.
    """
    return f"""Analyze the following news information about {topic}. 
    Search Results: {search_results}
    
    Please provide a comprehensive analysis including:
    1. Key Points Summary:
       - Main events and developments
       - Critical updates and changes
    
    2. Stakeholder Analysis:
       - Primary parties involved
       - Their roles and positions
    
    3. Impact Assessment:
       - Immediate implications
       - Potential long-term effects
       - Broader context and significance
    
    4. Multiple Perspectives:
       - Different viewpoints on the issue
       - Areas of agreement and contention
    
    5. Fact Check & Reliability:
       - Verification of major claims
       - Consistency across sources
       - Source credibility assessment
    
    Please format the analysis in a clear, journalistic style with section headers."""

def log_agent_activity(prompt: str, result: str, agent_name: str):
    """
    Creates an expandable log of agent activities in the Streamlit interface
    for transparency and debugging purposes.
    """
    with st.expander("πŸ” View Agent Activity Log"):
        st.markdown("<h4>Agent Activity Log</h4>", unsafe_allow_html=True)
        st.markdown(f"<p><strong>Agent:</strong> {agent_name}</p>", unsafe_allow_html=True)
        
        st.markdown("<div style='background-color: #f8f9fa; padding: 1rem; border-radius: 8px; margin-bottom: 1rem;'>", unsafe_allow_html=True)
        st.markdown("<p><strong>Input Prompt:</strong></p>", unsafe_allow_html=True)
        st.code(prompt, language="text")
        st.markdown("</div>", unsafe_allow_html=True)
        
        st.markdown("<div style='background-color: #f8f9fa; padding: 1rem; border-radius: 8px;'>", unsafe_allow_html=True)
        st.markdown("<p><strong>Analysis Output:</strong></p>", unsafe_allow_html=True)
        st.code(result, language="text")
        st.markdown("</div>", unsafe_allow_html=True)

# Animated header with branded logo and description
st.markdown("""
<div class="card" style="padding-bottom: 1.5rem;">
    <div style="display: flex; align-items: center; gap: 1.5rem;">
        <div class="float-icon" style="text-align: center;">
            <svg width="70" height="70" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M19.5 9.5l-7.5-7.5-7.5 7.5m15 0v8c0 1.1-.9 2-2 2h-11c-1.1 0-2-.9-2-2v-8" stroke="#1a73e8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <circle cx="12" cy="12" r="3" stroke="#1a73e8" stroke-width="2"/>
                <path d="M12 15v3" stroke="#1a73e8" stroke-width="2" stroke-linecap="round"/>
            </svg>
        </div>
        <div style="flex: 1;">
            <span class="logo-text">Z-Agent News Analysis</span>
            <p style="color: #5f6368; font-size: 1.1rem; margin-top: 0.5rem;">
                Intelligent news analysis powered by AI. Get comprehensive insights and multiple perspectives on any topic.
            </p>
        </div>
    </div>
</div>
""", unsafe_allow_html=True)

# Main content area
st.markdown('<div class="card">', unsafe_allow_html=True)

# Initialize the components
try:
    # Initialize LLM and search tool
    llm = GroqLLM()
    search_tool = DuckDuckGoSearch()
    
    # Input section with enhanced design
    st.markdown("<h2 style='margin-top: 0;'>News Topic Analysis</h2>", unsafe_allow_html=True)
    
    news_topic = st.text_input(
        "What news topic would you like to analyze?",
        placeholder="E.g., Recent developments in renewable energy, Tech industry layoffs, Global climate agreements...",
        key="news_topic_input"
    )
    
    # Analysis options in a cleaner layout
    st.markdown("<div style='margin-top: 1.5rem;'></div>", unsafe_allow_html=True)
    st.markdown("<h3 style='margin-bottom: 1rem;'>Analysis Options</h3>", unsafe_allow_html=True)
    
    col1, col2, col3 = st.columns([2, 2, 2])
    
    with col1:
        st.markdown("<div style='background-color: #f8f9fa; padding: 1rem; border-radius: 12px; height: 100%;'>", unsafe_allow_html=True)
        st.markdown("<p style='font-weight: 600; color: #202124; margin-bottom: 0.5rem;'>Search Depth</p>", unsafe_allow_html=True)
        search_depth = st.slider(
            "##",
            min_value=3,
            max_value=10,
            value=5,
            help="Number of news sources to analyze",
            key="search_depth_slider",
            label_visibility="collapsed"
        )
        st.markdown("<p style='color: #5f6368; font-size: 0.9rem;'>Number of sources: " + str(search_depth) + "</p>", unsafe_allow_html=True)
        st.markdown("</div>", unsafe_allow_html=True)
    
    with col2:
        st.markdown("<div style='background-color: #f8f9fa; padding: 1rem; border-radius: 12px; height: 100%;'>", unsafe_allow_html=True)
        st.markdown("<p style='font-weight: 600; color: #202124; margin-bottom: 0.5rem;'>Analysis Type</p>", unsafe_allow_html=True)
        analysis_type = st.selectbox(
            "##",
            ["Comprehensive", "Quick Summary", "Technical", "Simplified"],
            help="Choose the style and depth of analysis",
            key="analysis_type_select",
            label_visibility="collapsed"
        )
        st.markdown("<p style='color: #5f6368; font-size: 0.9rem;'>Selected: " + analysis_type + "</p>", unsafe_allow_html=True)
        st.markdown("</div>", unsafe_allow_html=True)
    
    with col3:
        st.markdown("<div style='background-color: #f8f9fa; padding: 1rem; border-radius: 12px; height: 100%;'>", unsafe_allow_html=True)
        st.markdown("<p style='font-weight: 600; color: #202124; margin-bottom: 0.5rem;'>Time Period</p>", unsafe_allow_html=True)
        time_period = st.selectbox(
            "##",
            ["Last 7 days", "Last 30 days", "Last 24 hours"],
            help="How recent should the news be",
            key="time_period_select",
            label_visibility="collapsed"
        )
        st.markdown("<p style='color: #5f6368; font-size: 0.9rem;'>Selected: " + time_period + "</p>", unsafe_allow_html=True)
        st.markdown("</div>", unsafe_allow_html=True)
    
    # Generate analysis button
    st.markdown("<div style='margin-top: 2rem;'></div>", unsafe_allow_html=True)
    
    col1, col2, col3 = st.columns([2, 2, 2])
    
    with col2:
        analyze_button = st.button("ANALYZE NEWS")
    
    st.markdown('</div>', unsafe_allow_html=True)
    
    # Results section
    if analyze_button and news_topic:
        with st.spinner(""):
            try:
                # Progress indicators with enhanced styling
                progress_container = st.container()
                progress_container.markdown('<div class="info-box">', unsafe_allow_html=True)
                progress_placeholder = progress_container.empty()
                progress_placeholder.markdown("""
                <div class="pulsing">
                    <div class="status-badge status-searching">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="11" cy="11" r="8"></circle>
                            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                        </svg>
                        <span>Searching for recent news sources...</span>
                    </div>
                </div>
                """, unsafe_allow_html=True)
                
                # Determine time frame from selection
                time_map = {
                    "Last 24 hours": "24h",
                    "Last 7 days": "7d",
                    "Last 30 days": "30d"
                }
                time_frame = time_map.get(time_period, "7d")
                
                # Perform search
                search_results = search_tool(
                    f"Latest news about {news_topic} {time_frame}",
                    max_results=search_depth
                )
                
                if not search_results.startswith(("Search error", "No results")):
                    # Update progress
                    progress_placeholder.markdown("""
                    <div class="pulsing">
                        <div class="status-badge status-analyzing">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M12 3v3m0 12v3m-9-9H3m3-6l2 2M3 12h3m12 0h3m-3-6l-2 2m9 3h-3m-6 6l-2 2m12 0l-2-2"></path>
                            </svg>
                            <span>Analyzing search results and generating insights...</span>
                        </div>
                    </div>
                    """, unsafe_allow_html=True)
                    
                    # Create analysis prompt
                    analysis_prompt = create_analysis_prompt(news_topic, search_results)
                    
                    # Get analysis from LLM
                    analysis_result = llm(analysis_prompt)
                    
                    # Clear progress messages
                    progress_container.empty()
                    
                    # Display results in tabs for better organization
                    st.markdown('<div class="card">', unsafe_allow_html=True)
                    st.markdown(f'<h2>Analysis: {news_topic}</h2>', unsafe_allow_html=True)
                    
                    tab1, tab2 = st.tabs(["πŸ“Š Analysis", "πŸ“° Sources"])
                    
                    with tab1:
                        st.markdown('<div class="analysis-result">', unsafe_allow_html=True)
                        st.markdown(analysis_result)
                        st.markdown('</div>', unsafe_allow_html=True)
                    
                    with tab2:
                        st.markdown("<h3>News Sources Used in Analysis</h3>", unsafe_allow_html=True)
                        # Parse and display sources in a more structured way
                        sources = search_results.split("\n\n")
                        for source in sources:
                            lines = source.strip().split("\n")
                            if len(lines) >= 5:  # Ensure we have enough lines
                                title_line = lines[0].replace("1. Title: ", "").replace("2. Title: ", "").replace("3. Title: ", "").replace("4. Title: ", "").replace("5. Title: ", "")
                                date_line = lines[1].replace("   Date: ", "")
                                source_line = lines[2].replace("   Source: ", "")
                                url_line = lines[4].replace("   URL: ", "")
                                
                                st.markdown(f"""
                                <div class="source-item">
                                    <p class="source-title">{title_line}</p>
                                    <div class="source-meta">
                                        <span>{source_line}</span>
                                        <span class="source-meta-dot"></span>
                                        <span>{date_line}</span>
                                    </div>
                                    <a href="{url_line}" class="read-link" target="_blank">
                                        Read original article
                                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"></path>
                                            <path d="M15 3h6v6"></path>
                                            <path d="M10 14L21 3"></path>
                                        </svg>
                                    </a>
                                </div>
                                """, unsafe_allow_html=True)
                    
                    st.markdown('</div>', unsafe_allow_html=True)
                    
                    # Log the activity
                    log_agent_activity(
                        analysis_prompt,
                        analysis_result,
                        "News Analysis Agent"
                    )
                else:
                    progress_container.empty()
                    st.error(f"""
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FF5252" stroke-width="2">
                            <circle cx="12" cy="12" r="10"></circle>
                            <line x1="12" y1="8" x2="12" y2="12"></line>
                            <line x1="12" y1="16" x2="12.01" y2="16"></line>
                        </svg>
                        <span>{search_results}</span>
                    </div>
                    """, unsafe_allow_html=True)
                    
            except Exception as e:
                st.error(f"""
                <div style="display: flex; align-items: center; gap: 12px;">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FF5252" stroke-width="2">
                        <circle cx="12" cy="12" r="10"></circle>
                        <line x1="12" y1="8" x2="12" y2="12"></line>
                        <line x1="12" y1="16" x2="12.01" y2="16"></line>
                    </svg>
                    <span>An error occurred during analysis: {str(e)}</span>
                </div>
                """, unsafe_allow_html=True)
    elif analyze_button:
        # This handles the case when analyze button is clicked but no topic is entered
        st.warning("""
        <div style="display: flex; align-items: center; gap: 12px;">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FFA726" stroke-width="2">
                <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"></path>
                <line x1="12" y1="9" x2="12" y2="13"></line>
                <line x1="12" y1="17" x2="12.01" y2="17"></line>
            </svg>
            <span>Please enter a news topic to analyze.</span>
        </div>
        """, unsafe_allow_html=True)

    # Tips and usage guidance section - displayed when no analysis is in progress
    if not analyze_button or not news_topic:
        st.markdown('<div class="card">', unsafe_allow_html=True)
        st.markdown("<h2 style='margin-top: 0;'>Tips for Better Results</h2>", unsafe_allow_html=True)
        
        st.markdown("""
        <div class="tip-item">
            <div class="tip-icon">πŸ’‘</div>
            <div class="tip-text">
                <strong>Be specific with your topic.</strong> Instead of "climate change", try "recent climate legislation in the EU".
            </div>
        </div>
        
        <div class="tip-item">
            <div class="tip-icon">πŸ”</div>
            <div class="tip-text">
                <strong>Adjust search depth</strong> to find the right balance between comprehensive coverage and analysis speed.
            </div>
        </div>
        
        <div class="tip-item">
            <div class="tip-icon">πŸ“Š</div>
            <div class="tip-text">
                <strong>Choose the right analysis type</strong> based on your needs:
                <ul>
                    <li><strong>Comprehensive:</strong> Full analysis with multiple perspectives</li>
                    <li><strong>Quick Summary:</strong> Brief overview of key points</li>
                    <li><strong>Technical:</strong> Detailed analysis with industry-specific terminology</li>
                    <li><strong>Simplified:</strong> Easy-to-understand breakdown of complex topics</li>
                </ul>
            </div>
        </div>
        
        <div class="tip-item">
            <div class="tip-icon">⏱️</div>
            <div class="tip-text">
                <strong>Select an appropriate time period</strong> based on how recent you want the news to be.
            </div>
        </div>
        """, unsafe_allow_html=True)
        
        st.markdown('</div>', unsafe_allow_html=True)
        
        # Example topics for quick selection
        st.markdown('<div class="card">', unsafe_allow_html=True)
        st.markdown("<h2 style='margin-top: 0;'>Try These Topics</h2>", unsafe_allow_html=True)
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            if st.button("🌍 Climate Change Policies"):
                st.session_state.news_topic_input = "Recent climate change policies and agreements"
                st.experimental_rerun()
                
        with col2:
            if st.button("πŸ’° Cryptocurrency Trends"):
                st.session_state.news_topic_input = "Latest developments in cryptocurrency markets"
                st.experimental_rerun()
                
        with col3:
            if st.button("πŸ”¬ AI Research Breakthroughs"):
                st.session_state.news_topic_input = "Recent breakthroughs in artificial intelligence research"
                st.experimental_rerun()
                
        st.markdown('</div>', unsafe_allow_html=True)

    # Footer with attribution and version info
    st.markdown("""
    <footer>
        <div style="display: flex; justify-content: space-between; align-items: center;">
            <div>Z-Agent News Analysis v1.0.1</div>
            <div>Powered by Groq LLM & DuckDuckGo Search</div>
        </div>
    </footer>
    """, unsafe_allow_html=True)

except Exception as e:
    # Global error handling to catch any unforeseen issues
    st.error(f"""
    <div style="display: flex; align-items: center; gap: 12px;">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FF5252" stroke-width="2">
            <circle cx="12" cy="12" r="10"></circle>
            <line x1="12" y1="8" x2="12" y2="12"></line>
            <line x1="12" y1="16" x2="12.01" y2="16"></line>
        </svg>
        <span>Application Error: {str(e)}</span>
    </div>
    """, unsafe_allow_html=True)
    
    st.markdown("""
    <div style="background-color: #F8F9FA; padding: 1rem; border-radius: 8px; margin-top: 1rem;">
        <p><strong>Troubleshooting Tips:</strong></p>
        <ul>
            <li>Check your API keys for Groq LLM in environment variables</li>
            <li>Ensure you have internet connection for DuckDuckGo searches</li>
            <li>Try refreshing the page or restarting the application</li>
        </ul>
    </div>
    """, unsafe_allow_html=True)

# Add a hidden feature to reset the application state
if st.sidebar.button("Reset Application", key="reset_app"):
    for key in st.session_state.keys():
        del st.session_state[key]
    st.experimental_rerun()

# Optional: Add a feedback mechanism
with st.sidebar:
    st.markdown("### Feedback")
    feedback = st.text_area("Share your thoughts or report issues", placeholder="Your feedback helps us improve...")
    if st.button("Submit Feedback"):
        st.success("Thank you for your feedback!")
        # In a production app, you would save this feedback to a database