File size: 24,366 Bytes
60c933d
 
355fee6
60c933d
 
33871a2
 
7e17d80
33871a2
 
 
 
3c4c999
33871a2
 
60c933d
 
0fae2b4
1dec737
cc9f818
1dec737
60c933d
 
 
0fae2b4
b8116ac
2bc9710
0fae2b4
 
60c933d
 
 
 
 
a4dd0c9
60c933d
b8116ac
 
 
60c933d
2bc9710
 
355fee6
2bc9710
 
 
355fee6
2bc9710
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60c933d
7a682ac
e44799d
7a682ac
 
e44799d
 
 
 
 
 
 
 
 
 
 
 
3803d82
e44799d
 
 
 
 
a4dd0c9
 
e44799d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3803d82
e44799d
 
 
 
 
a4dd0c9
 
e44799d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4dd0c9
 
 
 
 
 
 
 
 
7a682ac
 
60c933d
355fee6
60c933d
 
 
 
 
 
 
 
 
 
 
 
355fee6
 
 
 
 
 
 
 
3c4c999
355fee6
 
 
 
 
 
 
3c4c999
355fee6
3c4c999
 
 
355fee6
 
3c4c999
355fee6
 
 
3c4c999
355fee6
 
 
 
 
 
 
 
 
 
 
 
 
33871a2
355fee6
 
 
 
 
 
 
 
 
 
 
33871a2
 
 
355fee6
3c4c999
33871a2
355fee6
 
 
 
 
 
3c4c999
355fee6
3c4c999
355fee6
e44799d
33871a2
3c4c999
 
 
 
 
 
 
355fee6
3c4c999
 
 
 
 
 
 
 
 
 
33871a2
355fee6
33871a2
 
355fee6
33871a2
 
355fee6
33871a2
 
 
 
e44799d
3c4c999
 
 
 
 
 
33871a2
3c4c999
33871a2
cc9f818
3c4c999
 
 
 
 
 
 
 
 
355fee6
 
 
 
 
 
 
 
 
 
 
 
e44799d
355fee6
 
 
 
3c4c999
 
355fee6
 
 
 
 
 
 
 
e44799d
355fee6
 
 
 
3c4c999
 
355fee6
 
 
 
 
 
 
 
 
60c933d
2bc9710
60c933d
 
 
 
b8116ac
9afda58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60c933d
 
 
b8116ac
9afda58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60c933d
 
 
9afda58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60c933d
b8116ac
9afda58
b8116ac
 
 
60c933d
 
9afda58
 
 
 
33871a2
 
9afda58
355fee6
9afda58
 
355fee6
9afda58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60c933d
 
9afda58
60c933d
2bc9710
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e44799d
60c933d
 
b8116ac
33871a2
 
 
 
 
3c4c999
33871a2
b8116ac
3c4c999
60c933d
b8116ac
7a682ac
e44799d
 
 
 
 
 
2bc9710
7a682ac
 
2bc9710
7a682ac
3c4c999
7a682ac
e44799d
60c933d
0fae2b4
60c933d
 
 
b8116ac
 
 
 
 
 
 
 
2bc9710
9afda58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e44799d
3c4c999
355fee6
9afda58
355fee6
b8116ac
 
0fae2b4
3c4c999
 
60c933d
2a8b709
355fee6
1dec737
0fae2b4
3c4c999
0fae2b4
 
b8116ac
 
 
 
 
60c933d
2a8b709
b8116ac
1dec737
3c4c999
0fae2b4
 
60c933d
b8116ac
60c933d
 
2a8b709
b8116ac
 
0fae2b4
 
60c933d
b8116ac
60c933d
 
 
 
 
 
 
 
b8116ac
60c933d
 
 
0fae2b4
e44799d
0fae2b4
 
60c933d
b8116ac
 
 
 
 
 
 
 
3c4c999
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fae2b4
 
2bc9710
cc9f818
3c4c999
cc9f818
 
33871a2
b8116ac
1dec737
b8116ac
355fee6
1dec737
b8116ac
1dec737
0fae2b4
b8116ac
 
0fae2b4
b8116ac
 
 
 
 
 
3c4c999
b8116ac
 
60c933d
b8116ac
 
60c933d
b8116ac
 
1dec737
b8116ac
1dec737
b8116ac
 
1dec737
b8116ac
 
1dec737
 
b8116ac
 
 
 
 
 
 
 
 
60c933d
 
b8116ac
1dec737
 
b8116ac
 
 
 
0fae2b4
b8116ac
1dec737
 
b8116ac
3c4c999
0fae2b4
b8116ac
 
 
60c933d
0fae2b4
 
60c933d
0fae2b4
 
 
b8116ac
 
 
 
2bc9710
 
 
 
a4dd0c9
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
# ============================================================
#                    X-RUDRA CHAT
#          Dual‑Model + Web Research · Gradio Space
# ============================================================

# ──────────────────────────────────────────────────────────────
#  REASONING‑ENFORCED AGENT CONTRACT (AGENT.md)
#  See full policy in the multi‑line comment below.
# ──────────────────────────────────────────────────────────────

"""
# REASONING-ENFORCED AGENT
... (full policy – keep as before)
"""

from __future__ import annotations

import os
import json
import re
import time
import asyncio
import traceback

import gradio as gr
import spaces
from gradio_client import Client


# ============================================================
# CONFIG
# ============================================================

APP_NAME = "X-RUDRA"
VERSION = "3.8.3"   # bumped

M1_REPO = os.getenv("M1_REPO", "Shrijanagain/M1")
M2_REPO = os.getenv("M2_REPO", "Shrijanagain/M2")
PORT = int(os.getenv("PORT", "7860"))

HF_TOKEN = os.getenv("HF_TOKEN")
if HF_TOKEN:
    os.environ["HF_TOKEN"] = HF_TOKEN


# ============================================================
# GRADIO CLIENTS FOR M1 / M2
# ============================================================

_M1_CLIENT = None
_M2_CLIENT = None

def get_m1_client():
    global _M1_CLIENT
    if _M1_CLIENT is None:
        try:
            url = f"https://{M1_REPO.replace('/', '-')}.hf.space"
            _M1_CLIENT = Client(url)
        except Exception as e:
            print(f"Could not connect to M1: {e}")
            _M1_CLIENT = None
    return _M1_CLIENT

def get_m2_client():
    global _M2_CLIENT
    if _M2_CLIENT is None:
        try:
            url = f"https://{M2_REPO.replace('/', '-')}.hf.space"
            _M2_CLIENT = Client(url)
        except Exception as e:
            print(f"Could not connect to M2: {e}")
            _M2_CLIENT = None
    return _M2_CLIENT


# ============================================================
# MODEL-BASED INTENT CLASSIFIER
# ============================================================

CLASSIFIER_SYSTEM_PROMPT = """
You are an intelligent assistant that classifies user messages into two categories:
- ACTION: The user asks for information that requires research, fact‑checking, retrieval of current data, or external knowledge. This includes questions about news, comparisons, statistics, history, technology, science, politics, etc.
- CASUAL: The user is just chatting, greeting, making small talk, joking, or asking a simple question that can be answered from general knowledge without a search.

Respond with ONLY ONE WORD: ACTION or CASUAL.
Do NOT add any extra text, punctuation, or explanation.
"""

def classify_intent(question: str) -> str:
    prompt = f"{CLASSIFIER_SYSTEM_PROMPT}\n\nUser message: \"{question}\"\n\nClassification:"
    
    # Try M1
    m1_client = get_m1_client()
    if m1_client is not None:
        try:
            result = m1_client.predict(
                prompt=prompt,
                max_tokens=64,
                temperature=0.1,          # FIXED: was 0.0 → now 0.1
                api_name="/generate"
            )
            if result:
                result = result.strip().upper()
                if "ACTION" in result:
                    print(f"[Classifier] M1 → ACTION")
                    return "ACTION"
                elif "CASUAL" in result:
                    print(f"[Classifier] M1 → CASUAL")
                    return "CASUAL"
                else:
                    print(f"[Classifier] M1 ambiguous: {result}")
        except Exception as e:
            print(f"[Classifier] M1 call failed: {e}")

    # Try M2
    m2_client = get_m2_client()
    if m2_client is not None:
        try:
            result = m2_client.predict(
                prompt=prompt,
                max_tokens=64,
                temperature=0.1,          # FIXED
                api_name="/generate"
            )
            if result:
                result = result.strip().upper()
                if "ACTION" in result:
                    print(f"[Classifier] M2 → ACTION")
                    return "ACTION"
                elif "CASUAL" in result:
                    print(f"[Classifier] M2 → CASUAL")
                    return "CASUAL"
                else:
                    print(f"[Classifier] M2 ambiguous: {result}")
        except Exception as e:
            print(f"[Classifier] M2 call failed: {e}")

    # Fallback: if both fail, use simple heuristic (no keyword list)
    # For very short messages (<=3 words), assume CASUAL to avoid unnecessary search.
    word_count = len(question.split())
    if word_count <= 3:
        print("[Classifier] Fallback → CASUAL (short message)")
        return "CASUAL"
    else:
        print("[Classifier] Fallback → ACTION (longer message)")
        return "ACTION"


# ============================================================
# LAZY ENGINE (web search)
# ============================================================

_ENGINE = None

def get_engine():
    global _ENGINE
    if _ENGINE is None:
        from web_search import XrudraWebSearch
        _ENGINE = XrudraWebSearch()
    return _ENGINE


# ============================================================
# HELPERS – CALL MODELS
# ============================================================

def call_model(client, prompt, max_tokens=512, temperature=0.7):
    if client is None:
        return None
    try:
        print(f"Calling model with max_tokens={max_tokens}, prompt length={len(prompt)}")
        result = client.predict(
            prompt=prompt,
            max_tokens=max_tokens,
            temperature=temperature,
            api_name="/generate"
        )
        if result and isinstance(result, str) and result.strip():
            print(f"Response length: {len(result)} chars")
            return result.strip()
        else:
            print("Empty response")
            return None
    except Exception as e:
        print(f"Model call failed: {e}")
        return None


# ============================================================
# SYNTHESIS: M1 + M2 drafts → M2 merges (with higher token budget)
# ============================================================

def get_combined_model_answer(question, sources, max_tokens=512, temperature=0.7):
    top_sources = sources[:5] if sources else []
    sources_text = ""
    if top_sources:
        for i, src in enumerate(top_sources, 1):
            title = src.get("title", "Untitled")
            snippet = src.get("snippet", src.get("description", ""))
            sources_text += f"{i}. {title}: {snippet[:300]}\n"
    else:
        sources_text = "No specific information available."

    base_prompt = f"""Question: {question}

Information:
{sources_text}

Based on the information above and your knowledge, provide a comprehensive, accurate, and well‑structured answer to the question. Be direct and natural – write as if you are an expert answering a user.

Answer:"""

    m1_client = get_m1_client()
    m2_client = get_m2_client()

    # ----- 1. Get independent drafts from M1 and M2 -----
    draft_m1 = call_model(m1_client, base_prompt, max_tokens, temperature)
    draft_m2 = call_model(m2_client, base_prompt, max_tokens, temperature)

    # Fallback if both fail
    if not draft_m1 and not draft_m2:
        if sources:
            parts = ["Based on available information:"]
            for i, src in enumerate(sources[:5], 1):
                title = src.get("title", "Untitled")
                snippet = src.get("snippet", src.get("description", ""))
                parts.append(f"{i}. {title}: {snippet[:200]}..." if snippet else f"{i}. {title}")
            return "\n\n".join(parts), ""
        else:
            return "I couldn't find specific information on that topic. Could you rephrase?", ""

    # If only one draft exists, use that as final
    if not draft_m1:
        thinking = ""
        clean = draft_m2
        think_match = re.search(r"<think>(.*?)</think>", draft_m2, re.DOTALL)
        if think_match:
            thinking = think_match.group(1).strip()
            clean = re.sub(r"<think>.*?</think>", "", draft_m2, flags=re.DOTALL).strip()
        return clean, thinking

    if not draft_m2:
        thinking = ""
        clean = draft_m1
        think_match = re.search(r"<think>(.*?)</think>", draft_m1, re.DOTALL)
        if think_match:
            thinking = think_match.group(1).strip()
            clean = re.sub(r"<think>.*?</think>", "", draft_m1, flags=re.DOTALL).strip()
        return clean, thinking

    # ----- 2. Merge both drafts using M2 with a larger token budget -----
    merge_prompt = f"""Question: {question}

Draft from Model A:
{draft_m1}

Draft from Model B:
{draft_m2}

Combine these two drafts into a single, comprehensive, accurate, and natural answer. Keep the best parts from each. Ensure the final answer directly addresses the question, is well‑structured, and reads as a single coherent response. Do NOT mention that you are combining drafts or that you used multiple models. Just provide the final answer.

Final answer:"""

    merge_max_tokens = max(1024, max_tokens * 2)
    merged = call_model(m2_client, merge_prompt, merge_max_tokens, temperature)

    if merged and len(merged) < 100:
        print(f"Merged answer too short ({len(merged)} chars), retrying with 2048 tokens...")
        merged = call_model(m2_client, merge_prompt, 2048, temperature)

    if not merged:
        print("Merge failed, falling back to draft_m1")
        merged = draft_m1

    # Extract thinking and clean tags
    thinking_content = ""
    clean_answer = merged
    think_match = re.search(r"<think>(.*?)</think>", merged, re.DOTALL)
    if think_match:
        thinking_content = think_match.group(1).strip()
        clean_answer = re.sub(r"<think>.*?</think>", "", merged, flags=re.DOTALL).strip()

    return clean_answer, thinking_content


# ============================================================
# CASUAL REPLY (calls M1 or M2)
# ============================================================

def get_casual_model_response(query: str) -> str:
    client = get_m1_client()
    if client is not None:
        try:
            result = client.predict(
                prompt=f"User: {query}\nAssistant:",
                max_tokens=128,
                temperature=0.7,
                api_name="/generate"
            )
            if result and isinstance(result, str) and result.strip():
                clean = re.sub(r"<think>.*?</think>", "", result, flags=re.DOTALL).strip()
                return clean
        except Exception as e:
            print(f"M1 casual failed: {e}")

    client = get_m2_client()
    if client is not None:
        try:
            result = client.predict(
                prompt=f"User: {query}\nAssistant:",
                max_tokens=128,
                temperature=0.7,
                api_name="/generate"
            )
            if result and isinstance(result, str) and result.strip():
                clean = re.sub(r"<think>.*?</think>", "", result, flags=re.DOTALL).strip()
                return clean
        except Exception as e:
            print(f"M2 casual failed: {e}")

    return (
        f"👋 Hi there! I'm X‑RUDRA, your research assistant. "
        f"How can I help you today? (Your message `{query}` was casual, so I kept it light.)"
    )


# ============================================================
# FORMATTERS (Sources, Evidence, Verification)
# ============================================================

def format_sources(sources):
    if not sources:
        return "## 📚 Sources\n\nNo sources were returned."
    output = ["## 📚 Sources", ""]
    for idx, src in enumerate(sources, 1):
        if not isinstance(src, dict):
            continue
        title = src.get("title", "Untitled")
        url = src.get("url", "")
        method = src.get("fetch_method", "web")
        score = src.get("source_score", src.get("score", "N/A"))
        snippet = src.get("snippet", src.get("description", ""))
        if url:
            output.append(f"### {idx}. [{title}]({url})")
        else:
            output.append(f"### {idx}. {title}")
        output.append(f"**Fetcher:** `{method}`")
        output.append(f"**Source score:** `{score}`")
        if snippet:
            output.append(f"\n> {snippet}")
        output.append("")
    return "\n".join(output)


def format_evidence(claims):
    if not claims:
        return "## 🧠 Evidence\n\nNo structured evidence was returned."
    output = ["## 🧠 Evidence", ""]
    for idx, claim in enumerate(claims, 1):
        if not isinstance(claim, dict):
            continue
        text = claim.get("claim", claim.get("text", ""))
        score = claim.get("support_score", claim.get("score", "N/A"))
        source = claim.get("source_url", claim.get("url", ""))
        output.append(f"### Evidence {idx}")
        output.append(str(text))
        output.append(f"**Support:** `{score}`")
        if source:
            output.append(f"**Source:** {source}")
        output.append("---")
    return "\n\n".join(output)


def format_verification(contradictions):
    if not contradictions:
        return "## ⚖️ Verification\n\n✅ No major contradictions detected."
    output = ["## ⚖️ Verification", "", "⚠️ Potential contradictions detected:", ""]
    for idx, item in enumerate(contradictions, 1):
        if not isinstance(item, dict):
            continue
        claim_a = item.get("claim_a", "")
        claim_b = item.get("claim_b", "")
        source_a = item.get("source_a", "")
        source_b = item.get("source_b", "")
        output.append(f"### Contradiction {idx}")
        output.append(f"**A:** {claim_a}")
        if source_a:
            output.append(f"Source A: `{source_a}`")
        output.append("")
        output.append(f"**B:** {claim_b}")
        if source_b:
            output.append(f"Source B: `{source_b}`")
        output.append("---")
    return "\n\n".join(output)


def build_activity(data, elapsed_ms):
    sources = data.get("sources", []) or data.get("results", [])
    claims = data.get("claims", [])
    contradictions = data.get("contradictions", [])
    rounds = data.get("rounds", data.get("research_rounds", "N/A"))
    return f"""
## ⚡ X-RUDRA Research

| Stage | Status |
|---|---|
| Task analysis | ✅ Complete |
| M1 research | ✅ Draft generated |
| M2 research | ✅ Draft generated + merged |
| Web discovery | ✅ Complete |
| Evidence extraction | {"✅" if claims else "⚙️"} |
| Source verification | ✅ Complete |
| Contradiction check | {"⚠️ Found" if contradictions else "✅ Clear"} |
| Final synthesis | ✅ Complete |

**Sources:** `{len(sources)}`  
**Claims:** `{len(claims)}`  
**Rounds:** `{rounds}`  
**Time:** `{elapsed_ms} ms`

### Engine

`M1` → `{M1_REPO}`

`M2` → `{M2_REPO}`

`Web` → `DuckDuckGo`

`Fetcher` → `Scrapling`

`Browser` → `Playwright`
"""


# ============================================================
# SAFE DICT HELPER
# ============================================================

def safe_dict(value):
    if isinstance(value, dict):
        return value
    if hasattr(value, "model_dump"):
        try:
            return value.model_dump()
        except Exception:
            pass
    if hasattr(value, "dict"):
        try:
            return value.dict()
        except Exception:
            pass
    return {"result": str(value)}


# ============================================================
# MAIN RESEARCH FUNCTION
# ============================================================

async def do_research(question, max_results, max_rounds, use_models, freshness):
    empty_history = []
    empty_activity = "⚪ Enter a question to start."
    empty_sources = ""
    empty_evidence = ""
    empty_verification = ""
    empty_thinking = ""

    if not question or not str(question).strip():
        return empty_history, empty_activity, empty_sources, empty_evidence, empty_verification, empty_thinking

    question = str(question).strip()

    # ---- Step 1: Classify intent using M1 (or M2) ----
    intent = classify_intent(question)
    print(f"[Intent] {intent} for: {question}")

    # ---- Step 2: If casual, reply directly ----
    if intent == "CASUAL":
        answer = get_casual_model_response(question)
        history = [
            {"role": "user", "content": question},
            {"role": "assistant", "content": answer}
        ]
        return history, "⚡ Casual chat (model reply, no search).", "", "", "", ""

    # ---- Step 3: ACTION – run research pipeline ----
    started = time.perf_counter()
    try:
        engine = get_engine()
        report = await engine.search(
            question=question,
            max_results=int(max_results),
            max_rounds=int(max_rounds),
            use_models=bool(use_models),
            freshness_mode=str(freshness),
        )
        data = safe_dict(report)
        elapsed_ms = int((time.perf_counter() - started) * 1000)

        # Convert 'results' to 'sources' if needed
        sources = data.get("sources", [])
        if not sources:
            results = data.get("results", [])
            for res in results:
                if isinstance(res, dict):
                    sources.append({
                        "title": res.get("title", ""),
                        "url": res.get("url", ""),
                        "snippet": res.get("snippet", ""),
                        "fetch_method": "web",
                        "source_score": res.get("rank", "N/A"),
                        "description": res.get("snippet", ""),
                    })
            data["sources"] = sources

        # Generate final answer and thinking
        final_answer, thinking_content = get_combined_model_answer(question, sources)

        sources_md = format_sources(sources)
        evidence_md = format_evidence(data.get("claims", []))
        verification_md = format_verification(data.get("contradictions", []))
        activity_md = build_activity(data, elapsed_ms)

        thinking_md = f"### 🧠 Reasoning\n\n{thinking_content}" if thinking_content else ""

        history = [
            {"role": "user", "content": question},
            {"role": "assistant", "content": final_answer}
        ]

        return history, activity_md, sources_md, evidence_md, verification_md, thinking_md

    except Exception as exc:
        error = f"❌ **X-RUDRA Error**\n\n`{type(exc).__name__}: {exc}`"
        print("\n" + "="*70)
        print("X-RUDRA ERROR")
        print(traceback.format_exc())
        print("="*70 + "\n")
        history = [
            {"role": "user", "content": question},
            {"role": "assistant", "content": error}
        ]
        return history, "❌ Research failed.", "", "", "", ""


# ============================================================
# GRADIO SYNC WRAPPER WITH @spaces.GPU
# ============================================================

@spaces.GPU
def run_research(question, max_results, max_rounds, use_models, freshness):
    return asyncio.run(do_research(question, max_results, max_rounds, use_models, freshness))


# ============================================================
# HEALTH CHECK
# ============================================================

def health_check():
    return f"""
## 🟢 X-RUDRA Online
**Version:** `{VERSION}`
**M1:** `{M1_REPO}`
**M2:** `{M2_REPO}`
**Engine:** Lazy initialized
"""


# ============================================================
# CSS
# ============================================================

CSS = """
body { background: #f7f7f8; }
.gradio-container { max-width: 1500px !important; }
#header { text-align: center; padding: 20px 0 10px 0; }
#logo { font-size: 38px; font-weight: 800; }
#tagline { opacity: 0.65; font-size: 15px; }
#chat { border-radius: 18px; }
#send { min-height: 52px; font-size: 18px; font-weight: 700; }
footer { display: none !important; }

@keyframes think-pulse {
    0% { opacity: 0.3; transform: scale(0.95); }
    50% { opacity: 1; transform: scale(1.05); }
    100% { opacity: 0.3; transform: scale(0.95); }
}
.thinking-spinner {
    display: inline-block;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: #6b7280;
    margin-right: 8px;
    animation: think-pulse 1.2s ease-in-out infinite;
}
.thinking-container {
    background: #f3f4f6;
    border-left: 4px solid #6366f1;
    padding: 12px 16px;
    border-radius: 8px;
    margin: 12px 0;
    font-family: monospace;
    white-space: pre-wrap;
    word-wrap: break-word;
}
"""


# ============================================================
# GRADIO UI – 6 outputs
# ============================================================

with gr.Blocks(title=APP_NAME) as demo:
    gr.HTML("""
        <div id="header">
            <div id="logo">⚡ X-RUDRA</div>
            <div id="tagline">Dual‑Model AI · Live Web Research · Evidence</div>
        </div>
    """)

    with gr.Row():
        with gr.Column(scale=7):
            chatbot = gr.Chatbot(label="X-RUDRA", height=600, elem_id="chat")
            with gr.Row():
                question = gr.Textbox(placeholder="Ask X-RUDRA anything...", lines=2, show_label=False, scale=8)
                send = gr.Button("➤", variant="primary", elem_id="send", scale=1)

        with gr.Column(scale=4):
            gr.Markdown("## 🔬 Live Research")
            activity = gr.Markdown("⚪ Waiting for your question.")
            thinking = gr.Markdown("", visible=True)
            gr.Markdown("---")
            gr.Markdown(f"""
### Model Spaces
**M1** `{M1_REPO}`
**M2** `{M2_REPO}`
### Web Stack
`DuckDuckGo` · `Scrapling` · `Playwright`
""")

    with gr.Accordion("⚙️ Research Controls", open=False):
        with gr.Row():
            max_results = gr.Slider(1, 30, value=10, step=1, label="Max Sources")
            max_rounds = gr.Slider(1, 5, value=3, step=1, label="Research Rounds")
        with gr.Row():
            use_models = gr.Checkbox(value=True, label="Use M1 + M2")
            freshness = gr.Dropdown(["auto","latest","recent","current"], value="auto", label="Freshness")

    with gr.Tabs():
        with gr.Tab("📚 Sources"):
            sources = gr.Markdown("Sources will appear here.")
        with gr.Tab("🧠 Evidence"):
            evidence = gr.Markdown("Evidence will appear here.")
        with gr.Tab("⚖️ Verification"):
            verification = gr.Markdown("Verification will appear here.")

    with gr.Accordion("🩺 System Health", open=False):
        health_button = gr.Button("Check X-RUDRA")
        health_output = gr.Markdown()

    gr.Markdown("### Try X-RUDRA")
    gr.Examples(
        examples=[
            ["What are the latest UNESCO AI education initiatives?"],
            ["What are the latest developments in open source AI?"],
            ["Compare the latest major AI models."],
            ["Research India's current AI ecosystem."]
        ],
        inputs=question
    )

    inputs = [question, max_results, max_rounds, use_models, freshness]
    outputs = [chatbot, activity, sources, evidence, verification, thinking]

    send.click(fn=run_research, inputs=inputs, outputs=outputs)
    question.submit(fn=run_research, inputs=inputs, outputs=outputs)
    health_button.click(fn=health_check, inputs=[], outputs=[health_output])


# ============================================================
# START
# ============================================================

if __name__ == "__main__":
    print(f"Starting {APP_NAME} {VERSION}")
    print("M1:", M1_REPO)
    print("M2:", M2_REPO)
    print("Lazy engine initialization: ON")
    if HF_TOKEN:
        print("HF_TOKEN set – rate limits reduced.")
    else:
        print("HF_TOKEN not set – you may experience rate limits. Set it as a Secret in your Space.")
    demo.launch(server_name="0.0.0.0", server_port=PORT, css=CSS, show_error=True)