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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac24bf9
7cbe8ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04e28a8
7cbe8ed
 
ac24bf9
 
 
 
 
 
 
5e3eb6a
ac24bf9
 
 
 
 
 
 
5e3eb6a
ac24bf9
 
 
 
 
 
 
 
 
 
 
 
 
7cbe8ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac24bf9
 
 
7cbe8ed
 
ac24bf9
 
 
 
 
7cbe8ed
 
 
 
ac24bf9
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
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
import threading
import queue
import time
import spaces
import sys
from io import StringIO
import re

# Model configuration
model_name = "HelpingAI/Dhanishtha-2.0-preview"

# Global variables for model and tokenizer
model = None
tokenizer = None

def load_model():
    """Load the model and tokenizer"""
    global model, tokenizer

    print("Loading tokenizer...")
    tokenizer = AutoTokenizer.from_pretrained(model_name)

    # Ensure pad token is set
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token

    print("Loading model...")
    model = AutoModelForCausalLM.from_pretrained(
        model_name,
        torch_dtype="auto",
        device_map="auto",
        trust_remote_code=True
    )

    print("Model loaded successfully!")

class StreamCapture:
    """Capture streaming output from TextStreamer"""
    def __init__(self):
        self.text_queue = queue.Queue()
        self.captured_text = ""
        
    def write(self, text):
        """Capture written text"""
        if text and text.strip():
            self.captured_text += text
            self.text_queue.put(text)
        return len(text)
    
    def flush(self):
        """Flush method for compatibility"""
        pass
    
    def get_text(self):
        """Get all captured text"""
        return self.captured_text
    
    def reset(self):
        """Reset the capture"""
        self.captured_text = ""
        while not self.text_queue.empty():
            try:
                self.text_queue.get_nowait()
            except queue.Empty:
                break

def format_thinking_text(text):
    """Format text to properly display <think> and <ser> tags in Gradio with styled borders"""
    if not text:
        return text

    # More sophisticated formatting for thinking and SER blocks
    formatted_text = text

    # Handle thinking blocks with proper HTML-like styling for Gradio
    thinking_pattern = r'<think>(.*?)</think>'

    def replace_thinking_block(match):
        thinking_content = match.group(1).strip()
        # Use HTML div with inline CSS for blue border styling like HelpingAI
        return f'''

<div style="border-left: 4px solid #4a90e2; background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 100%); padding: 16px 20px; margin: 16px 0; border-radius: 12px; font-family: 'Segoe UI', sans-serif; box-shadow: 0 2px 8px rgba(74, 144, 226, 0.15); border: 1px solid rgba(74, 144, 226, 0.2);">
<div style="color: #4a90e2; font-weight: 600; margin-bottom: 10px; display: flex; align-items: center; font-size: 14px;">
<span style="margin-right: 8px;">🧠</span> Think
</div>
<div style="color: #2c3e50; line-height: 1.6; font-size: 14px;">
{thinking_content}
</div>
</div>

'''

    # Handle SER blocks with purple/violet styling and structured formatting
    ser_pattern = r'<ser>(.*?)</ser>'

    def replace_ser_block(match):
        ser_content = match.group(1).strip()
        
        # Parse structured SER content if it follows the pattern
        ser_lines = ser_content.split('\n')
        formatted_content = []
        
        for line in ser_lines:
            line = line.strip()
            if not line:
                continue
                
            # Check if line has the "Key ==> Value" pattern
            if ' ==> ' in line:
                parts = line.split(' ==> ', 1)
                if len(parts) == 2:
                    key = parts[0].strip()
                    value = parts[1].strip()
                    formatted_content.append(f'<div style="margin: 8px 0;"><strong style="color: #8e44ad;">{key}:</strong> <span style="color: #2c3e50;">{value}</span></div>')
                else:
                    formatted_content.append(f'<div style="margin: 4px 0; color: #2c3e50;">{line}</div>')
            else:
                formatted_content.append(f'<div style="margin: 4px 0; color: #2c3e50;">{line}</div>')
        
        if not formatted_content:
            formatted_content = [f'<div style="color: #2c3e50; line-height: 1.6;">{ser_content}</div>']
        
        content_html = ''.join(formatted_content)
        
        # Use HTML div with inline CSS for purple border styling for SER
        return f'''

<div style="border-left: 4px solid #8e44ad; background: linear-gradient(135deg, #f8f4ff 0%, #ede7f6 100%); padding: 16px 20px; margin: 16px 0; border-radius: 12px; font-family: 'Segoe UI', sans-serif; box-shadow: 0 2px 8px rgba(142, 68, 173, 0.15); border: 1px solid rgba(142, 68, 173, 0.2);">
<div style="color: #8e44ad; font-weight: 600; margin-bottom: 10px; display: flex; align-items: center; font-size: 14px;">
<span style="margin-right: 8px;">πŸ’œ</span> SER (Structured Emotional Reasoning)
</div>
<div style="line-height: 1.6; font-size: 14px;">
{content_html}
</div>
</div>

'''

    formatted_text = re.sub(thinking_pattern, replace_thinking_block, formatted_text, flags=re.DOTALL)
    formatted_text = re.sub(ser_pattern, replace_ser_block, formatted_text, flags=re.DOTALL)

    # Clean up any remaining raw tags that might not have been caught
    formatted_text = re.sub(r'</?think>', '', formatted_text)
    formatted_text = re.sub(r'</?ser>', '', formatted_text)

    return formatted_text.strip()

@spaces.GPU()
def generate_response(message, history, max_tokens, temperature, top_p):
    """Generate streaming response with improved TextStreamer"""
    global model, tokenizer
    
    if model is None or tokenizer is None:
        yield "Model is still loading. Please wait..."
        return
    
    # Prepare conversation history
    messages = []
    for user_msg, assistant_msg in history:
        messages.append({"role": "user", "content": user_msg})
        if assistant_msg:
            messages.append({"role": "assistant", "content": assistant_msg})
    
    # Add current message
    messages.append({"role": "user", "content": message})
    
    # Apply chat template
    text = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )
    
    # Tokenize input
    model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
    
    # Create stream capture
    stream_capture = StreamCapture()
    
    # Create TextStreamer with our capture - don't skip special tokens to preserve <think> and <ser>
    streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=False)
    
    # Temporarily redirect the streamer's output
    original_stdout = sys.stdout
    
    # Generation parameters
    generation_kwargs = {
        **model_inputs,
        "max_new_tokens": max_tokens,
        "temperature": temperature,
        "top_p": top_p,
        "do_sample": True,
        "pad_token_id": tokenizer.eos_token_id,
        "streamer": streamer,
    }
    
    # Start generation in a separate thread
    def generate():
        try:
            # Redirect stdout to capture streamer output
            sys.stdout = stream_capture
            with torch.no_grad():
                model.generate(**generation_kwargs)
        except Exception as e:
            stream_capture.text_queue.put(f"Error: {str(e)}")
        finally:
            # Restore stdout
            sys.stdout = original_stdout
            stream_capture.text_queue.put(None)  # Signal end
    
    thread = threading.Thread(target=generate)
    thread.start()
    
    # Stream the results with formatting
    generated_text = ""
    while True:
        try:
            new_text = stream_capture.text_queue.get(timeout=30)
            if new_text is None:
                break
            generated_text += new_text
            # Format and yield the current text with <think> and <ser> blocks
            formatted_text = format_thinking_text(generated_text)
            yield formatted_text
        except queue.Empty:
            break
    
    thread.join(timeout=1)
    
    # Final yield with complete formatted text
    if generated_text:
        final_text = format_thinking_text(generated_text)
        yield final_text
    else:
        yield "No response generated."

def chat_interface(message, history, max_tokens, temperature, top_p):
    """Main chat interface with improved streaming for messages format"""
    if not message.strip():
        return history, ""

    # Add user message to history (messages format)
    history.append({"role": "user", "content": message})

    # Generate response with streaming
    # Convert messages format to tuples for generate_response compatibility
    history_tuples = []
    for i in range(0, len(history) - 1, 2):  # Process pairs
        user_msg = history[i] if i < len(history) else None
        assistant_msg = history[i + 1] if i + 1 < len(history) else None
        
        if user_msg and user_msg.get("role") == "user":
            user_content = user_msg.get("content", "")
            assistant_content = assistant_msg.get("content", "") if assistant_msg and assistant_msg.get("role") == "assistant" else ""
            history_tuples.append([user_content, assistant_content])
    
    # Add assistant message placeholder
    history.append({"role": "assistant", "content": ""})
    
    # Generate response with streaming
    for partial_response in generate_response(message, history_tuples, max_tokens, temperature, top_p):
        history[-1]["content"] = partial_response
        yield history, ""

    return history, ""

# Load model on startup
print("Initializing model...")
load_model()

# Custom CSS for modern, professional styling
custom_css = """
/* Import Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');

/* Global styling */
.gradio-container {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
}

/* Main container styling */
.main {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 24px;
    box-shadow: 0 20px 40px rgba(0,0,0,0.1);
    margin: 20px;
    padding: 32px;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

/* Header styling */
.gradio-markdown h1 {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-weight: 700;
    font-size: 3rem;
    text-align: center;
    margin-bottom: 1rem;
    text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.gradio-markdown h3 {
    color: #4a5568;
    font-weight: 600;
    margin-top: 1.5rem;
    margin-bottom: 0.5rem;
}

/* Chatbot styling */
.chatbot {
    font-size: 15px;
    font-family: 'Inter', sans-serif;
    background: #ffffff;
    border-radius: 20px;
    border: 1px solid #e2e8f0;
    box-shadow: 0 8px 32px rgba(0,0,0,0.08);
    overflow: hidden;
}

.chatbot .message {
    padding: 16px 20px;
    margin: 8px 12px;
    border-radius: 16px;
    line-height: 1.6;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    transition: all 0.2s ease;
}

.chatbot .message:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

/* User message styling */
.chatbot .message.user {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    margin-left: 15%;
    border-bottom-right-radius: 6px;
    box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

/* Assistant message styling */
.chatbot .message.bot {
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    color: #2d3748;
    margin-right: 15%;
    border-bottom-left-radius: 6px;
    border: 1px solid #e2e8f0;
}

/* Enhanced thinking and SER block styling */
.thinking-block, .ser-block {
    border-radius: 12px;
    padding: 16px 20px;
    margin: 16px 0;
    font-family: 'Inter', sans-serif;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    position: relative;
    overflow: hidden;
}

.thinking-block::before, .ser-block::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #4a90e2, #357abd);
}

/* Input styling */
.gradio-textbox {
    border-radius: 16px;
    border: 2px solid #e2e8f0;
    transition: all 0.3s ease;
    font-family: 'Inter', sans-serif;
    padding: 16px 20px;
    font-size: 15px;
    background: #ffffff;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.gradio-textbox:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
    outline: none;
}

/* Button styling */
.gradio-button {
    border-radius: 14px;
    font-weight: 600;
    font-family: 'Inter', sans-serif;
    transition: all 0.3s ease;
    padding: 12px 24px;
    font-size: 14px;
    letter-spacing: 0.5px;
    border: none;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.gradio-button.primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

.gradio-button.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
}

.gradio-button.secondary {
    background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
    color: #4a5568;
    border: 1px solid #e2e8f0;
}

.gradio-button.secondary:hover {
    background: linear-gradient(135deg, #edf2f7 0%, #e2e8f0 100%);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

/* Slider styling */
.gradio-slider {
    margin: 12px 0;
}

.gradio-slider input[type="range"] {
    -webkit-appearance: none;
    height: 6px;
    border-radius: 3px;
    background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e0 100%);
    outline: none;
}

.gradio-slider input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    cursor: pointer;
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
    transition: all 0.2s ease;
}

.gradio-slider input[type="range"]::-webkit-slider-thumb:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* Examples styling */
.gradio-examples {
    margin-top: 24px;
    background: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(10px);
    border-radius: 16px;
    padding: 20px;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.gradio-examples .gradio-button {
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid #e2e8f0;
    color: #4a5568;
    font-size: 13px;
    padding: 12px 16px;
    margin: 4px;
    border-radius: 12px;
    transition: all 0.2s ease;
    backdrop-filter: blur(10px);
}

.gradio-examples .gradio-button:hover {
    background: rgba(255, 255, 255, 1);
    color: #2d3748;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

/* Code block styling */
pre {
    background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
    color: #e2e8f0;
    border-radius: 12px;
    padding: 20px;
    overflow-x: auto;
    font-family: 'JetBrains Mono', 'Consolas', 'Monaco', monospace;
    font-size: 14px;
    line-height: 1.5;
    box-shadow: 0 4px 16px rgba(0,0,0,0.1);
    border: 1px solid #4a5568;
}

/* Sidebar styling */
.gradio-column {
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
    border-radius: 16px;
    padding: 20px;
    margin: 8px;
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-shadow: 0 4px 16px rgba(0,0,0,0.05);
}

/* Footer styling */
.gradio-markdown hr {
    border: none;
    height: 1px;
    background: linear-gradient(90deg, transparent, #e2e8f0, transparent);
    margin: 2rem 0;
}

/* Responsive design */
@media (max-width: 768px) {
    .main {
        margin: 10px;
        padding: 20px;
        border-radius: 16px;
    }
    
    .gradio-markdown h1 {
        font-size: 2rem;
    }
    
    .chatbot .message.user,
    .chatbot .message.bot {
        margin-left: 5%;
        margin-right: 5%;
    }
}

/* Loading animation */
.loading {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 3px solid rgba(102, 126, 234, 0.3);
    border-radius: 50%;
    border-top-color: #667eea;
    animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

/* Scroll styling */
::-webkit-scrollbar {
    width: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}
"""

# Create Gradio interface with modern design
with gr.Blocks(
    title="πŸ€– Dhanishtha-2.0-preview | Advanced Reasoning AI",
    theme=gr.themes.Soft(
        primary_hue="blue",
        secondary_hue="purple",
        neutral_hue="slate",
        font=gr.themes.GoogleFont("Inter"),
        font_mono=gr.themes.GoogleFont("JetBrains Mono")
    ),
    css=custom_css,
    head="<link rel='icon' href='πŸ€–' type='image/svg+xml'>"
) as demo:
    # Header Section
    gr.HTML("""
    <div style="text-align: center; padding: 2rem 0; background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%); border-radius: 20px; margin-bottom: 2rem; border: 1px solid rgba(102, 126, 234, 0.2);">
        <h1 style="margin: 0; font-size: 3.5rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-weight: 800;">
            πŸ€– Dhanishtha-2.0-preview
        </h1>
        <p style="font-size: 1.2rem; color: #64748b; margin: 1rem 0; font-weight: 500;">
            Advanced Reasoning AI with Transparent Thinking Process
        </p>
        <div style="display: flex; justify-content: center; gap: 2rem; flex-wrap: wrap; margin-top: 1.5rem;">
            <div style="background: rgba(74, 144, 226, 0.1); padding: 0.8rem 1.5rem; border-radius: 12px; border: 1px solid rgba(74, 144, 226, 0.2);">
                <span style="color: #4a90e2; font-weight: 600;">🧠 Multi-step Reasoning</span>
            </div>
            <div style="background: rgba(142, 68, 173, 0.1); padding: 0.8rem 1.5rem; border-radius: 12px; border: 1px solid rgba(142, 68, 173, 0.2);">
                <span style="color: #8e44ad; font-weight: 600;">πŸ’œ Emotional Intelligence</span>
            </div>
            <div style="background: rgba(34, 197, 94, 0.1); padding: 0.8rem 1.5rem; border-radius: 12px; border: 1px solid rgba(34, 197, 94, 0.2);">
                <span style="color: #22c55e; font-weight: 600;">πŸ”„ Real-time Streaming</span>
            </div>
        </div>
    </div>
    """)
    
    # Main Chat Interface
    with gr.Row(equal_height=True):
        with gr.Column(scale=4, min_width=600):
            # Chat Area
            with gr.Group():
                chatbot = gr.Chatbot(
                    [],
                    elem_id="chatbot",
                    height=650,
                    show_copy_button=True,
                    show_share_button=True,
                    type='messages',  # Use openai-style messages format
                    avatar_images=(
                        "https://raw.githubusercontent.com/gradio-app/gradio/main/gradio/themes/utils/profile_avatar.png", 
                        "πŸ€–"
                    ),
                    render_markdown=True,
                    sanitize_html=False,  # Allow HTML for thinking blocks
                    latex_delimiters=[
                        {"left": "$$", "right": "$$", "display": True},
                        {"left": "$", "right": "$", "display": False}
                    ]
                )

            # Input Section
            with gr.Group():
                with gr.Row():
                    msg = gr.Textbox(
                        container=False,
                        placeholder="πŸ’­ Ask me anything! I'll show you my thinking and emotional reasoning process...",
                        label="",
                        autofocus=True,
                        scale=8,
                        lines=1,
                        max_lines=5
                    )
                    with gr.Column(scale=1, min_width=120):
                        send_btn = gr.Button(
                            "πŸš€ Send", 
                            variant="primary", 
                            size="lg"
                        )
                        clear_btn = gr.Button(
                            "πŸ—‘οΈ Clear", 
                            variant="secondary", 
                            size="sm"
                        )

        # Settings Sidebar
        with gr.Column(scale=1, min_width=350):
            with gr.Group():
                gr.HTML("""
                <div style="text-align: center; padding: 1rem; background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%); border-radius: 12px; margin-bottom: 1rem;">
                    <h3 style="margin: 0; color: #667eea; font-weight: 600;">βš™οΈ Generation Settings</h3>
                </div>
                """)

                max_tokens = gr.Slider(
                    minimum=1,
                    maximum=40960,
                    value=2048,
                    step=1,
                    label="🎯 Max Tokens",
                    info="Maximum number of tokens to generate"
                )

                temperature = gr.Slider(
                    minimum=0.1,
                    maximum=2.0,
                    value=0.7,
                    step=0.1,
                    label="🌑️ Temperature",
                    info="Controls randomness in generation"
                )

                top_p = gr.Slider(
                    minimum=0.1,
                    maximum=1.0,
                    value=0.9,
                    step=0.05,
                    label="🎲 Top-p (Nucleus Sampling)",
                    info="Controls diversity of generation"
                )

                with gr.Row():
                    stop_btn = gr.Button(
                        "⏹️ Stop Generation", 
                        variant="stop", 
                        size="sm"
                    )

            # Model Information Panel
            with gr.Group():
                gr.HTML("""
                <div style="background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(59, 130, 246, 0.1) 100%); border-radius: 12px; padding: 1.5rem; border: 1px solid rgba(34, 197, 94, 0.2);">
                    <h3 style="margin: 0 0 1rem 0; color: #22c55e; font-weight: 600;">πŸ“Š Model Information</h3>
                    <div style="color: #64748b; line-height: 1.6;">
                        <strong style="color: #1e293b;">Model:</strong> HelpingAI/Dhanishtha-2.0-preview<br>
                        <strong style="color: #1e293b;">Type:</strong> Advanced Reasoning LLM<br>
                        <strong style="color: #1e293b;">Features:</strong> Multi-step reasoning, emotional intelligence<br>
                        <strong style="color: #1e293b;">Special:</strong> Transparent thinking process with &lt;think&gt; and &lt;ser&gt; blocks
                    </div>
                </div>
                """)

            # Performance Stats (placeholder)
            with gr.Group():
                gr.HTML("""
                <div style="background: linear-gradient(135deg, rgba(168, 85, 247, 0.1) 0%, rgba(236, 72, 153, 0.1) 100%); border-radius: 12px; padding: 1.5rem; border: 1px solid rgba(168, 85, 247, 0.2);">
                    <h3 style="margin: 0 0 1rem 0; color: #a855f7; font-weight: 600;">⚑ Performance</h3>
                    <div style="color: #64748b; line-height: 1.6;">
                        <strong style="color: #1e293b;">Status:</strong> <span style="color: #22c55e;">Active βœ…</span><br>
                        <strong style="color: #1e293b;">Response Mode:</strong> Streaming<br>
                        <strong style="color: #1e293b;">Reasoning:</strong> Enhanced<br>
                        <strong style="color: #1e293b;">Context:</strong> 8192 tokens
                    </div>
                </div>
                """)
    
    # Example Prompts Section
    with gr.Group():
        gr.HTML("""
        <div style="text-align: center; padding: 1.5rem; background: linear-gradient(135deg, rgba(245, 158, 11, 0.1) 0%, rgba(251, 146, 60, 0.1) 100%); border-radius: 16px; margin: 2rem 0; border: 1px solid rgba(245, 158, 11, 0.2);">
            <h3 style="margin: 0 0 1rem 0; color: #f59e0b; font-weight: 600;">πŸ’‘ Example Prompts</h3>
            <p style="color: #64748b; margin: 0;">Try these prompts to see the thinking and emotional reasoning process in action!</p>
        </div>
        """)
        
        gr.Examples(
            examples=[
                ["Hello! Can you introduce yourself and show me your thinking and emotional reasoning process?"],
                ["Solve this step by step: What is 15% of 240? Show your complete reasoning."],
                ["Explain quantum entanglement in simple terms with your thought process"],
                ["Write a short Python function to find the factorial of a number and explain your approach"],
                ["What are the pros and cons of renewable energy? Include your emotional perspective using SER."],
                ["Help me understand the difference between AI and machine learning with examples"],
                ["Create a haiku about artificial intelligence and explain your creative process"],
                ["Explain why the sky is blue using physics principles with step-by-step thinking"],
                ["What's your favorite type of conversation and why? Show your emotional reasoning using SER format."],
                ["How do you handle complex ethical dilemmas? Walk me through your thinking and emotional process."],
                ["Tell me about a time when you had to change your mind about something. Use both thinking and SER blocks."],
                ["What makes you feel most fulfilled in conversations? Use structured emotional reasoning."]
            ],
            inputs=msg,
            label="",
            examples_per_page=6
        )

    # Event handlers
    def clear_chat():
        """Clear the chat history"""
        return [], ""

    # Message submission events
    msg.submit(
        chat_interface,
        inputs=[msg, chatbot, max_tokens, temperature, top_p],
        outputs=[chatbot, msg],
        concurrency_limit=1,
        show_progress="minimal"
    )

    send_btn.click(
        chat_interface,
        inputs=[msg, chatbot, max_tokens, temperature, top_p],
        outputs=[chatbot, msg],
        concurrency_limit=1,
        show_progress="minimal"
    )

    # Clear chat event
    clear_btn.click(
        clear_chat,
        outputs=[chatbot, msg],
        show_progress=False
    )

    # Footer Section
    gr.HTML("""
    <div style="text-align: center; padding: 2rem; background: linear-gradient(135deg, rgba(71, 85, 105, 0.1) 0%, rgba(100, 116, 139, 0.1) 100%); border-radius: 16px; margin-top: 2rem; border: 1px solid rgba(71, 85, 105, 0.2);">
        <h3 style="color: #475569; font-weight: 600; margin-bottom: 1rem;">πŸ”§ Technical Specifications</h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; color: #64748b; line-height: 1.6;">
            <div>
                <strong style="color: #1e293b;">Model:</strong> HelpingAI/Dhanishtha-2.0-preview<br>
                <strong style="color: #1e293b;">Framework:</strong> Transformers + Gradio
            </div>
            <div>
                <strong style="color: #1e293b;">Features:</strong> Real-time streaming<br>
                <strong style="color: #1e293b;">Reasoning:</strong> Multi-step with transparency
            </div>
            <div>
                <strong style="color: #1e293b;">Special Tags:</strong> &lt;think&gt; and &lt;ser&gt; blocks<br>
                <strong style="color: #1e293b;">Sampling:</strong> Custom temperature & top-p
            </div>
        </div>
        <hr style="border: none; height: 1px; background: linear-gradient(90deg, transparent, #e2e8f0, transparent); margin: 1.5rem 0;">
        <p style="color: #64748b; margin: 0; font-size: 14px;">
            πŸš€ <strong>Built with ❀️ using Gradio and Transformers</strong> | 
            πŸ’‘ The first LLM to show transparent thinking and emotional reasoning processes
        </p>
    </div>
    """)

if __name__ == "__main__":
    demo.queue(
        max_size=30,
        default_concurrency_limit=2
    ).launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True,
        quiet=False,
        favicon_path="πŸ€–",
        show_tips=True,
        enable_queue=True
    )