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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os
import uuid
from datetime import datetime
from typing import Dict

import pandas as pd
import streamlit as st
from datasets import load_dataset
from dotenv import load_dotenv

from langgraph_agent import DataAnalystAgent

# Load environment variables
load_dotenv()

# Set up page config
st.set_page_config(
    page_title="πŸ€– LangGraph Data Analyst Agent",
    layout="wide",
    page_icon="πŸ€–",
    initial_sidebar_state="expanded",
)

# Custom CSS for styling
st.markdown(
    """
<style>
    /* Main theme colors */
    :root {
        --primary-color: #1f77b4;
        --secondary-color: #ff7f0e;
        --success-color: #2ca02c;
        --error-color: #d62728;
        --warning-color: #ff9800;
        --background-color: #0e1117;
        --card-background: #262730;
    }
    
    /* Custom styling for the main container */
    .main-header {
        background: linear-gradient(90deg, #1f77b4 0%, #ff7f0e 100%);
        padding: 2rem 1rem;
        border-radius: 10px;
        margin-bottom: 2rem;
        text-align: center;
        color: white;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    
    .main-header h1 {
        margin: 0;
        font-size: 2.5rem;
        font-weight: 700;
        text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
    }
    
    .main-header p {
        margin: 0.5rem 0 0 0;
        font-size: 1.2rem;
        opacity: 0.9;
    }
    
    /* Card styling */
    .info-card {
        background: var(--card-background);
        padding: 1.5rem;
        border-radius: 10px;
        border-left: 4px solid var(--primary-color);
        margin: 1rem 0;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    .success-card {
        background: linear-gradient(90deg, 
            rgba(44, 160, 44, 0.1) 0%, 
            rgba(44, 160, 44, 0.05) 100%);
        border-left: 4px solid var(--success-color);
        padding: 1rem;
        border-radius: 8px;
        margin: 1rem 0;
    }
    
    .error-card {
        background: linear-gradient(90deg, 
            rgba(214, 39, 40, 0.1) 0%, 
            rgba(214, 39, 40, 0.05) 100%);
        border-left: 4px solid var(--error-color);
        padding: 1rem;
        border-radius: 8px;
        margin: 1rem 0;
    }
    
    .memory-card {
        background: linear-gradient(90deg, 
            rgba(255, 127, 14, 0.1) 0%, 
            rgba(255, 127, 14, 0.05) 100%);
        border-left: 4px solid var(--secondary-color);
        padding: 1rem;
        border-radius: 8px;
        margin: 1rem 0;
    }
    
    /* Chat message styling */
    .user-message {
        background: linear-gradient(90deg, 
            rgba(31, 119, 180, 0.1) 0%, 
            rgba(31, 119, 180, 0.05) 100%);
        padding: 1rem;
        border-radius: 10px;
        margin: 0.5rem 0;
        border-left: 4px solid var(--primary-color);
    }
    
    .assistant-message {
        background: linear-gradient(90deg, 
            rgba(255, 127, 14, 0.1) 0%, 
            rgba(255, 127, 14, 0.05) 100%);
        padding: 1rem;
        border-radius: 10px;
        margin: 0.5rem 0;
        border-left: 4px solid var(--secondary-color);
    }
    
    .session-info {
        background: var(--card-background);
        padding: 1rem;
        border-radius: 8px;
        margin: 0.5rem 0;
        border: 1px solid rgba(255, 255, 255, 0.1);
        font-size: 0.9rem;
    }
    
    /* Animation for thinking indicator */
    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.5; }
        100% { opacity: 1; }
    }
    
    .thinking-indicator {
        animation: pulse 2s infinite;
    }
</style>
""",
    unsafe_allow_html=True,
)


# API configuration
def get_api_configuration():
    """Get API configuration from environment variables."""
    api_key = os.environ.get("NEBIUS_API_KEY") or os.environ.get("OPENAI_API_KEY")

    if not api_key:
        st.markdown(
            """
        <div class="error-card">
            <h3>πŸ”‘ API Key Configuration Required</h3>
            
            <h4>For Local Development:</h4>
            <ol>
                <li>Create a <code>.env</code> file in your project directory</li>
                <li>Add your API key: <code>NEBIUS_API_KEY=your_api_key_here</code></li>
                <li>Or use OpenAI: <code>OPENAI_API_KEY=your_api_key_here</code></li>
                <li>Restart the application</li>
            </ol>
            
            <h4>For Deployment:</h4>
            <ol>
                <li>Set environment variable <code>NEBIUS_API_KEY</code> or 
                    <code>OPENAI_API_KEY</code></li>
                <li>Restart your application</li>
            </ol>
        </div>
        """,
            unsafe_allow_html=True,
        )
        st.stop()

    return api_key


# Initialize the agent
@st.cache_resource
def get_agent(api_key: str) -> DataAnalystAgent:
    """Initialize and cache the LangGraph agent."""
    return DataAnalystAgent(api_key=api_key)


# Load dataset
@st.cache_data
def load_bitext_dataset():
    """Load and cache the Bitext dataset."""
    try:
        dataset = load_dataset(
            "bitext/Bitext-customer-support-llm-chatbot-training-dataset"
        )
        df = pd.DataFrame(dataset["train"])
        return df
    except Exception as e:
        st.error(f"Error loading dataset: {e}")
        return None


# Session management functions
def initialize_session():
    """Initialize session state variables."""
    if "session_id" not in st.session_state:
        st.session_state.session_id = str(uuid.uuid4())

    if "conversation_history" not in st.session_state:
        st.session_state.conversation_history = []

    if "user_profile" not in st.session_state:
        st.session_state.user_profile = {}

    if "current_thread_id" not in st.session_state:
        st.session_state.current_thread_id = st.session_state.session_id


def create_new_session():
    """Create a new session with a new thread ID."""
    st.session_state.session_id = str(uuid.uuid4())
    st.session_state.current_thread_id = st.session_state.session_id
    st.session_state.conversation_history = []
    st.session_state.user_profile = {}


def format_conversation_message(role: str, content: str, timestamp: str = None):
    """Format a conversation message for display."""
    if timestamp is None:
        timestamp = datetime.now().strftime("%H:%M:%S")

    if role == "human":
        return f"""
        <div class="user-message">
            <strong>πŸ‘€ You ({timestamp}):</strong><br>
            {content}
        </div>
        """
    else:
        return f"""
        <div class="assistant-message">
            <strong>πŸ€– Agent ({timestamp}):</strong><br>
            {content}
        </div>
        """


def display_user_profile(profile: Dict):
    """Display user profile information."""
    if not profile:
        return

    with st.expander("🧠 What I Remember About You", expanded=False):
        col1, col2 = st.columns(2)

        with col1:
            st.markdown("**Your Interests:**")
            interests = profile.get("interests", [])
            if interests:
                for interest in interests:
                    st.write(f"β€’ {interest}")
            else:
                st.write("_No interests recorded yet_")

            st.markdown("**Expertise Level:**")
            expertise = profile.get("expertise_level", "beginner")
            st.write(f"β€’ {expertise.title()}")

        with col2:
            st.markdown("**Your Preferences:**")
            preferences = profile.get("preferences", {})
            if preferences:
                for key, value in preferences.items():
                    st.write(f"β€’ {key}: {value}")
            else:
                st.write("_No preferences recorded yet_")

            st.markdown("**Recent Query Topics:**")
            query_history = profile.get("query_history", [])
            if query_history:
                for query in query_history[-3:]:  # Show last 3
                    st.write(f"β€’ {query[:50]}...")
            else:
                st.write("_No query history yet_")


def main():
    # Custom header
    st.markdown(
        """
    <div class="main-header">
        <h1>πŸ€– LangGraph Data Analyst Agent</h1>
        <p>Intelligent Analysis with Memory & Recommendations</p>
    </div>
    """,
        unsafe_allow_html=True,
    )

    # Initialize session
    initialize_session()

    # Get API configuration
    api_key = get_api_configuration()

    # Initialize agent
    agent = get_agent(api_key)

    # Load dataset
    with st.spinner("πŸ”„ Loading dataset..."):
        df = load_bitext_dataset()

    if df is None:
        st.markdown(
            """
        <div class="error-card">
            <h3>❌ Dataset Loading Failed</h3>
            <p>Failed to load dataset. Please check your connection and try again.</p>
        </div>
        """,
            unsafe_allow_html=True,
        )
        return

    # Success message
    st.markdown(
        f"""
    <div class="success-card">
        <h3>βœ… System Ready</h3>
        <p>Dataset loaded with <strong>{len(df):,}</strong> records. 
           LangGraph agent initialized with memory.</p>
    </div>
    """,
        unsafe_allow_html=True,
    )

    # Sidebar configuration
    with st.sidebar:
        st.markdown("## βš™οΈ Session Management")

        # Session ID management
        st.markdown("### πŸ†” Session Control")

        col1, col2 = st.columns(2)
        with col1:
            if st.button("πŸ†• New Session", use_container_width=True):
                create_new_session()
                st.rerun()

        with col2:
            if st.button("πŸ”„ Refresh", use_container_width=True):
                st.rerun()

        # Display session info
        st.markdown(
            f"""
        <div class="session-info">
            <strong>Current Session:</strong><br>
            <code>{st.session_state.current_thread_id[:8]}...</code><br>
            <strong>Messages:</strong> {len(st.session_state.conversation_history)}
        </div>
        """,
            unsafe_allow_html=True,
        )

        # Custom session ID input
        st.markdown("### πŸ”— Join Existing Session")
        custom_thread_id = st.text_input(
            "Enter Session ID:",
            placeholder="Enter full session ID to join...",
            help="Use this to resume a previous conversation",
        )

        if st.button("πŸ”— Join Session") and custom_thread_id:
            st.session_state.current_thread_id = custom_thread_id
            # Load conversation history for this thread
            history = agent.get_conversation_history(custom_thread_id)
            st.session_state.conversation_history = history
            # Load user profile for this thread
            profile = agent.get_user_profile(custom_thread_id)
            st.session_state.user_profile = profile
            st.success(f"Joined session: {custom_thread_id[:8]}...")
            st.rerun()

        st.markdown("---")

        # Dataset info
        st.markdown("### πŸ“Š Dataset Info")
        col1, col2 = st.columns(2)
        with col1:
            st.metric("πŸ“ Records", f"{len(df):,}")
        with col2:
            st.metric("πŸ“‚ Categories", len(df["category"].unique()))

        st.metric("🎯 Intents", len(df["intent"].unique()))

        # Quick examples
        st.markdown("### πŸ’‘ Try These Queries")
        example_queries = [
            "What are the most common categories?",
            "Show me examples of billing issues",
            "Summarize the refund category",
            "What should I query next?",
            "What do you remember about me?",
        ]

        for query in example_queries:
            if st.button(f"πŸ’¬ {query}", key=f"example_{hash(query)}"):
                st.session_state.pending_query = query
                st.rerun()

    # Main content area
    # Display user profile
    if st.session_state.user_profile:
        display_user_profile(st.session_state.user_profile)

    # Dataset information in expandable section
    with st.expander("πŸ“Š Dataset Information", expanded=False):
        st.markdown("### Dataset Details")

        metrics_col1, metrics_col2, metrics_col3, metrics_col4 = st.columns(4)
        with metrics_col1:
            st.metric("Total Records", f"{len(df):,}")
        with metrics_col2:
            st.metric("Columns", len(df.columns))
        with metrics_col3:
            st.metric("Categories", len(df["category"].unique()))
        with metrics_col4:
            st.metric("Intents", len(df["intent"].unique()))

        st.markdown("### Sample Data")
        st.dataframe(df.head(), use_container_width=True)

        st.markdown("### Category Distribution")
        st.bar_chart(df["category"].value_counts())

    # User input section
    st.markdown("## πŸ’¬ Chat with the Agent")

    # Handle pending query from sidebar
    has_pending_query = hasattr(st.session_state, "pending_query")
    if has_pending_query:
        user_question = st.session_state.pending_query
        delattr(st.session_state, "pending_query")
    else:
        user_question = st.text_input(
            "Ask your question:",
            placeholder="e.g., What are the most common customer issues?",
            key="user_input",
            help="Ask about statistics, examples, insights, or request recommendations",
        )

    # Submit button
    col1, col2, col3 = st.columns([1, 2, 1])
    with col2:
        submit_clicked = st.button("πŸš€ Send Message", use_container_width=True)

    # Process query
    if (submit_clicked or has_pending_query) and user_question:
        # Add user message to local history
        timestamp = datetime.now().strftime("%H:%M:%S")
        st.session_state.conversation_history.append(
            {"role": "human", "content": user_question, "timestamp": timestamp}
        )

        # Show thinking indicator
        thinking_placeholder = st.empty()
        thinking_placeholder.markdown(
            """
        <div class="thinking-indicator">
            <div class="info-card">
                βš™οΈ <strong>Agent is thinking...</strong> 
                Processing your query through the LangGraph workflow.
            </div>
        </div>
        """,
            unsafe_allow_html=True,
        )

        try:
            # Invoke the agent
            result = agent.invoke(user_question, st.session_state.current_thread_id)

            # Get the last assistant message
            assistant_response = None
            for msg in reversed(result["messages"]):
                if (
                    hasattr(msg, "content")
                    and msg.content
                    and not isinstance(msg, type(user_question))
                ):
                    # Check if this is an AI message (not human or tool message)
                    if not hasattr(msg, "tool_calls") or not msg.tool_calls:
                        if "human" not in str(type(msg)).lower():
                            content = msg.content

                            # Clean up Qwen model thinking tags
                            if "<think>" in content and "</think>" in content:
                                # Extract only the part after </think>
                                parts = content.split("</think>")
                                if len(parts) > 1:
                                    content = parts[1].strip()

                            assistant_response = content
                            break

            if not assistant_response:
                assistant_response = "I processed your query but couldn't generate a response. Please try again."

            # Add assistant response to local history
            st.session_state.conversation_history.append(
                {
                    "role": "assistant",
                    "content": assistant_response,
                    "timestamp": datetime.now().strftime("%H:%M:%S"),
                }
            )

            # Update user profile from agent state
            if result.get("user_profile"):
                st.session_state.user_profile = result["user_profile"]

        except Exception as e:
            error_msg = f"Sorry, I encountered an error: {str(e)}"
            st.session_state.conversation_history.append(
                {
                    "role": "assistant",
                    "content": error_msg,
                    "timestamp": datetime.now().strftime("%H:%M:%S"),
                }
            )

        finally:
            thinking_placeholder.empty()

        # Clear the input and rerun to show new messages
        st.rerun()

    # Display conversation
    if st.session_state.conversation_history:
        st.markdown("## πŸ’­ Conversation")

        # Display messages
        for i, message in enumerate(st.session_state.conversation_history):
            message_html = format_conversation_message(
                message["role"], message["content"], message.get("timestamp", "")
            )
            st.markdown(message_html, unsafe_allow_html=True)

            # Add separator except for last message
            if i < len(st.session_state.conversation_history) - 1:
                st.markdown("---")

        # Action buttons
        col1, col2, col3 = st.columns(3)

        with col1:
            if st.button("πŸ—‘οΈ Clear Chat"):
                st.session_state.conversation_history = []
                st.rerun()

        with col2:
            if st.button("πŸ’Ύ Export Chat"):
                chat_data = {
                    "session_id": st.session_state.current_thread_id,
                    "timestamp": datetime.now().isoformat(),
                    "conversation": st.session_state.conversation_history,
                    "user_profile": st.session_state.user_profile,
                }
                st.download_button(
                    label="πŸ“₯ Download JSON",
                    data=json.dumps(chat_data, indent=2),
                    file_name=f"chat_export_{st.session_state.current_thread_id[:8]}.json",
                    mime="application/json",
                )

        with col3:
            if st.button("πŸ€– Get Recommendations"):
                st.session_state.pending_query = "What should I query next?"
                st.rerun()

    # Instructions
    with st.expander("πŸ“‹ How to Use This Agent", expanded=False):
        st.markdown(
            """
        ### 🎯 Query Types Supported:
        
        **Structured Queries (Quantitative):**
        - "How many records are in each category?"
        - "Show me 5 examples of billing issues"
        - "What are the most common intents?"
        
        **Unstructured Queries (Qualitative):**
        - "Summarize the refund category"
        - "What patterns do you see in payment issues?"
        - "Analyze customer sentiment in billing conversations"
        
        **Memory & Recommendations:**
        - "What do you remember about me?"
        - "What should I query next?"
        - "Advise me what to explore"
        
        ### 🧠 Memory Features:
        - **Session Persistence:** Your conversations are saved across page reloads
        - **User Profile:** The agent learns about your interests and preferences
        - **Query History:** Past queries influence future recommendations
        - **Cross-Session:** Use session IDs to resume conversations later
        
        ### πŸ”§ Advanced Features:
        - **Multi-Agent Architecture:** Separate agents for different query types
        - **Tool Usage:** Dynamic tool selection based on your needs
        - **Interactive Recommendations:** Collaborative query refinement
        """
        )


if __name__ == "__main__":
    main()