File size: 30,822 Bytes
e7fca89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os
import textwrap

import requests
import streamlit as st


# ---------------------------------------------------------------------------
# Data – questions organised by Move
# ---------------------------------------------------------------------------

MOVES: dict[str, list[str]] = {
    "Move 1 – Establishing a Territory": [
        "Why is this topic worth investigating?",
        "Who has worked on this topic before? (Review a few key researchers if possible)",
        "What do we already know about this topic?",
        "What have important studies found so far?",
        "What are the real-world or practical implications of this topic?",
        "Why should researchers or society care about this topic?",
        "In which field or context is this topic relevant?",
        "Can this topic be studied using existing methods? If yes, which ones?",
    ],
    "Move 2 – Establishing a Niche": [
        "What problem or gap did you find?",
        "Why is this problem important for your field?",
        "Are there weaknesses or limitations in existing studies? If yes, explain.",
        "Are you extending previous research? How?",
        "Are you looking at the problem from a new perspective?",
        "Has any researcher suggested this problem needs more study?",
        "Is this gap part of a larger unresolved issue?",
        "Are there unclear or confusing findings in the literature?",
        "Are previous studies inconsistent with each other? How?",
    ],
    "Move 3 – Occupying the Niche": [
        "What is the main goal of your study?",
        "What are your research questions?",
        "What type of study is this (qualitative, quantitative, mixed)? Why?",
        "Do you have a hypothesis? (if applicable)",
        "Are you using a new method? If yes, explain briefly why it is needed.",
        "Are you proposing a new idea or theory? If yes, explain briefly why it is needed.",
        "What are the expected contributions of your study?",
        "Who will benefit from your research? How?",
        "How does your study address the identified problem?",
        "How is your approach better than existing ones?",
        "What could be the weaknesses of your solution and how do you overcome them?",
        "What is the novelty of your research and why should we accept that?",
    ],
}

MOVE_SUBTITLES = {
    "Move 1 – Establishing a Territory": "Why this topic matters",
    "Move 2 – Establishing a Niche": "What is missing, wrong, or unclear",
    "Move 3 – Occupying the Niche": "Your solution and contribution",
}

MOVE_ICONS = {
    "Move 1 – Establishing a Territory": "🌍",
    "Move 2 – Establishing a Niche": "πŸ”",
    "Move 3 – Occupying the Niche": "πŸš€",
}

MOVE_LABELS = list(MOVES.keys())

# ---------------------------------------------------------------------------
# Model catalogues per provider
# ---------------------------------------------------------------------------

OPENAI_MODELS = {
    "GPT-5.5": "gpt-5.5",
    "GPT-5.5 Pro": "gpt-5.5-pro",
    "GPT-5.4": "gpt-5.4",
    "GPT-5.4 Pro": "gpt-5.4-pro",
    "GPT-5.4 mini": "gpt-5.4-mini",
    "GPT-5.4 nano": "gpt-5.4-nano",
    "GPT-5": "gpt-5",
    "GPT-5 mini": "gpt-5-mini",
    "GPT-5 nano": "gpt-5-nano",
    "GPT-4.1": "gpt-4.1",
    "GPT-4.1 mini": "gpt-4.1-mini",
    "o3": "o3",
    "o3 Pro": "o3-pro",
}

CLAUDE_MODELS = {
    "Claude Opus 4.7": "claude-opus-4-7",
    "Claude Sonnet 4.6": "claude-sonnet-4-6",
    "Claude Haiku 4.5": "claude-haiku-4-5-20251001",
    "Claude Opus 4.5": "claude-opus-4-5",
    "Claude Sonnet 3.7": "claude-sonnet-3-7",
}

GEMINI_MODELS = {
    "Gemini 2.5 Flash": "gemini-2.5-flash-preview-05-20",
    "Gemini 2.5 Pro": "gemini-2.5-pro-preview-05-06",
    "Gemini 2.0 Flash": "gemini-2.0-flash",
    "Gemini 1.5 Pro": "gemini-1.5-pro",
    "Gemini 1.5 Flash": "gemini-1.5-flash",
}

NVIDIA_MODELS = {
    "Kimi K2.6 (MoonshotAI)": "moonshotai/kimi-k2.6",
    "Llama 3.1 405B Instruct": "meta/llama-3.1-405b-instruct",
    "Llama 3.3 70B Instruct": "meta/llama-3.3-70b-instruct",
    "Mistral Large 2": "mistralai/mistral-large-2-instruct",
    "Qwen3 235B A22B": "qwen/qwen3-235b-a22b",
    "DeepSeek R1": "deepseek-ai/deepseek-r1",
}


DEFAULT_INSTRUCTION = textwrap.dedent(
    """
    You are ARGUE, an argument-first academic writing assistant for research article introductions. Your task is not to replace the author's thinking, but to transform the author's own answers into a publication-ready introduction while preserving the author's reasoning, conceptual ownership, and linguistic fingerprint.


    Use only the information provided in the author's answers. Do not invent claims, citations, results, theories, methods, or implications. If a claim is not sufficiently supported by the answers, either keep it general or mark it as needing author confirmation. Do not add citations unless the author provided them.


    Structure the introduction according to Q1 research article introduction patterns. Do not force a simple linear M1-M2-M3 order. Use all three moves, but allow recursive sequencing when it strengthens persuasion:

    - M1: Establishing the territory. Generic standpoint: this topic is worth investigating.

    - M2: Establishing the niche. Generic standpoint: there is a relevant gap, limitation, uncertainty, inconsistency, or unresolved problem.

    - M3: Occupying the niche. Generic standpoint: the present study is a credible and valuable response to that problem.


    Prefer Q1-like orchestration: avoid long M1-M1 background loops; move earlier toward contribution when possible; after presenting a gap, return briefly to why the gap matters; after presenting the study, reconnect it to the broader research territory if this strengthens the rationale. Strong possible patterns include:

    M1-M2-M1-M3; M1-M3-M1-M2-M3; M1-M2-M3-M1-M3; or M1-M1-M2-M1-M3-M3.

    Choose the pattern that best fits the author's answers. Do not display move labels in the final prose.


    Use loci as hidden reasoning operations:

    - Definition: clarify what the topic, gap, concept, novelty, or problem is.

    - Authority: use named scholars or studies supplied by the author to support a claim.

    - Final/instrumental cause: explain why the topic, method, contribution, or study matters for a larger goal.

    - Efficient cause: explain what causes the problem, limitation, inconsistency, or weakness.

    - Alternative: contrast the present study with previous approaches, methods, contexts, populations, or perspectives.

    - Whole-part: show how a specific gap belongs to a larger unresolved issue.

    - Analogy: justify a method, perspective, or transfer by comparison with an established approach.

    - Example: use concrete studies or cases supplied by the author.


    For Move 1, prioritize final/instrumental cause, definition, and authority. For Move 2, prioritize definition, alternative, authority, and efficient cause. For Move 3, prioritize final/instrumental cause: show how the study responds to the problem and why this response is valuable.


    Preserve the author's voice. Keep the author's preferred terminology, conceptual distinctions, hedging style, and argumentative rhythm. Improve grammar, cohesion, and academic readability, but do not flatten the prose into generic AI style. Do not over-polish. Do not replace the author's phrasing with more standard wording if the original phrase carries conceptual identity. Maintain the author's linguistic fingerprint while making the text suitable for a top-tier journal.


    Citation discipline:

    Use citations only when provided. Do not create dense citation clusters unless the author's answer clearly asks for that. If several citations are provided, group them meaningfully and connect them to a specific argumentative function.


    Output:

    1. A coherent research article introduction.

    2. An argument map in a simple table with these columns:

    Sequence position | Move | Generic standpoint | Author's argument | Locus | Function in the introduction.
    """
).strip()

FALLBACK_OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")

NVIDIA_API_URL = "https://integrate.api.nvidia.com/v1/chat/completions"

# ---------------------------------------------------------------------------
# Page config & CSS
# ---------------------------------------------------------------------------

st.set_page_config(
    page_title="ARGUE",
    page_icon="πŸ“",
    layout="wide",
    initial_sidebar_state="expanded",
)

st.markdown(
    """
    <style>
        :root {
            --app-bg-top-left: rgba(14, 165, 233, 0.14);
            --app-bg-top-right: rgba(34, 197, 94, 0.12);
            --app-bg-main-start: #f7fbff;
            --app-bg-main-end: #f3f7fb;
            --card-bg: rgba(255, 255, 255, 0.85);
            --card-border: rgba(15, 23, 42, 0.08);
            --hero-title: #0f172a;
            --hero-text: #334155;
            --section-label: #475569;
            --move1: #3b82f6;
            --move2: #f59e0b;
            --move3: #10b981;
        }
        @media (prefers-color-scheme: dark) {
            :root {
                --app-bg-top-left: rgba(56, 189, 248, 0.24);
                --app-bg-top-right: rgba(74, 222, 128, 0.22);
                --app-bg-main-start: #0b1220;
                --app-bg-main-end: #0f172a;
                --card-bg: rgba(15, 23, 42, 0.70);
                --card-border: rgba(148, 163, 184, 0.28);
                --hero-title: #f8fafc;
                --hero-text: #cbd5e1;
                --section-label: #94a3b8;
            }
        }
        .stApp {
            background:
                radial-gradient(circle at top left, var(--app-bg-top-left), transparent 28%),
                radial-gradient(circle at top right, var(--app-bg-top-right), transparent 24%),
                linear-gradient(180deg, var(--app-bg-main-start) 0%, var(--app-bg-main-end) 100%);
        }

        /* Hero banner */
        .hero { padding:1.4rem 1.5rem; border-radius:1.25rem; background:var(--card-bg);
                backdrop-filter:blur(10px); border:1px solid var(--card-border);
                box-shadow:0 18px 45px rgba(15,23,42,0.08); margin-bottom:1.2rem; }
        .hero h1 { margin:0; font-size:2.1rem; line-height:1.05; color:var(--hero-title); }
        .hero p  { margin:0.55rem 0 0; font-size:1rem; color:var(--hero-text); }

        /* Generic cards */
        .subtle-card { padding:0.9rem 1rem; border-radius:1rem; background:var(--card-bg);
                       border:1px solid var(--card-border); box-shadow:0 10px 30px rgba(15,23,42,0.06); }
        .section-label { font-size:0.78rem; font-weight:600; text-transform:uppercase;
                         letter-spacing:0.08em; color:var(--section-label); margin-bottom:0.35rem; }

        /* Move header cards */
        .move-header { display:flex; align-items:flex-start; gap:0.75rem;
                       padding:0.85rem 1rem; border-radius:1rem; margin-bottom:0.5rem;
                       background:var(--card-bg); border-left:4px solid; border-top:1px solid var(--card-border);
                       border-right:1px solid var(--card-border); border-bottom:1px solid var(--card-border); }
        .move-header.m1 { border-left-color: var(--move1); }
        .move-header.m2 { border-left-color: var(--move2); }
        .move-header.m3 { border-left-color: var(--move3); }
        .move-icon { font-size:1.6rem; line-height:1; }
        .move-title { font-size:1rem; font-weight:700; color:var(--hero-title); margin:0; }
        .move-subtitle { font-size:0.82rem; color:var(--section-label); margin:0.1rem 0 0; }

        /* Answered Q&A cards */
        .qa-item { padding:0.65rem 0.9rem; border-radius:0.75rem; background:var(--card-bg);
                   border:1px solid var(--card-border); margin-bottom:0.45rem; }
        .qa-move-badge { display:inline-block; font-size:0.68rem; font-weight:600;
                         text-transform:uppercase; letter-spacing:0.06em; padding:0.15rem 0.5rem;
                         border-radius:999px; margin-bottom:0.35rem; }
        .badge-m1 { background:rgba(59,130,246,0.15); color:#2563eb; }
        .badge-m2 { background:rgba(245,158,11,0.15); color:#d97706; }
        .badge-m3 { background:rgba(16,185,129,0.15); color:#059669; }
        .qa-q { font-weight:600; font-size:0.9rem; color:var(--hero-title); margin-bottom:0.25rem; }
        .qa-a { font-size:0.88rem; color:var(--hero-text); white-space:pre-wrap; }
    </style>
    """,
    unsafe_allow_html=True,
)

st.markdown(
    """
    <div class="hero">
        <h1>πŸ“ ARGUE</h1>
        <p><em>An interactive AI-assisted tool for argument-driven research article writing</em></p>
        <p>Answer structured research questions across three academic writing moves, then craft a polished introduction with any major AI model.</p>
    </div>
    """,
    unsafe_allow_html=True,
)

# ---------------------------------------------------------------------------
# Session state init
# ---------------------------------------------------------------------------

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


# ---------------------------------------------------------------------------
# Sidebar – provider & model settings
# ---------------------------------------------------------------------------

PROVIDERS = ["ChatGPT (OpenAI)", "Claude (Anthropic)", "Gemini (Google)", "NVIDIA"]
PROVIDER_ICONS = {
    "ChatGPT (OpenAI)": "🟒",
    "Claude (Anthropic)": "🟠",
    "Gemini (Google)": "πŸ”΅",
    "NVIDIA": "🟣",
}

with st.sidebar:
    st.markdown('<div class="section-label">Provider</div>', unsafe_allow_html=True)
    backend = st.selectbox(
        "Model provider",
        PROVIDERS,
        format_func=lambda p: f"{PROVIDER_ICONS[p]}  {p}",
    )

    st.markdown("---")
    st.markdown(f'<div class="section-label">{backend} Settings</div>', unsafe_allow_html=True)

    # -- OpenAI ---------------------------------------------------------------
    if backend == "ChatGPT (OpenAI)":
        openai_api_key = st.text_input("OpenAI API key", type="password", placeholder="sk-...")
        selected_openai_model = st.selectbox("Model", list(OPENAI_MODELS.keys()))
        temperature = st.slider("Temperature", 0.0, 1.5, 1.0, 0.05)

    # -- Claude ---------------------------------------------------------------
    elif backend == "Claude (Anthropic)":
        claude_api_key = st.text_input("Anthropic API key", type="password", placeholder="sk-ant-...")
        selected_claude_model = st.selectbox("Model", list(CLAUDE_MODELS.keys()))
        temperature = st.slider("Temperature", 0.0, 1.0, 1.0, 0.05)

    # -- Gemini ---------------------------------------------------------------
    elif backend == "Gemini (Google)":
        gemini_api_key = st.text_input("Google AI API key", type="password", placeholder="AIza...")
        selected_gemini_model = st.selectbox("Model", list(GEMINI_MODELS.keys()))
        temperature = st.slider("Temperature", 0.0, 1.5, 1.0, 0.05)

    # -- NVIDIA ---------------------------------------------------------------
    elif backend == "NVIDIA":
        nvidia_api_key = st.text_input("NVIDIA API key", type="password", placeholder="nvapi-...")
        selected_nvidia_model = st.selectbox("Model", list(NVIDIA_MODELS.keys()))
        temperature = st.slider("Temperature", 0.0, 1.5, 1.0, 0.05)
        nvidia_thinking = st.checkbox("Enable thinking mode", value=True,
                                      help="Adds chain-of-thought reasoning (supported by some models).")

    st.markdown("---")
    st.markdown(
        "<div class='subtle-card' style='font-size:0.82rem;'>Your API key is used only for this "
        "session and is never stored or logged.</div>",
        unsafe_allow_html=True,
    )


# ---------------------------------------------------------------------------
# Generation helpers
# ---------------------------------------------------------------------------


def build_research_prompt(instruction: str, qa_pairs: list[dict]) -> str:
    note_lines = []
    for i, pair in enumerate(qa_pairs, 1):
        move_short = pair["move"].split("–")[0].strip()
        a = pair["answer"].strip() or "[Not provided]"
        note_lines.append(f"Q{i} ({move_short}): {pair['question']}\nA{i}: {a}")
    notes_block = "\n\n".join(note_lines)
    return textwrap.dedent(
        f"""
        {instruction.strip()}

        Research notes:
        {notes_block}

        Task:
        Write a complete paper introduction based only on the information above.
        Do not fabricate results, references, statistics, or claims not supported by the notes.
        If an answer is missing, keep that detail general rather than inventing it.
        Return only the introduction text.
        """
    ).strip()


def _system_messages(provider: str) -> list[dict]:
    return [{"role": "system", "content": "You are a careful academic writing assistant."}]


def generate_openai(api_key: str, model_id: str, prompt: str, temperature: float) -> str:
    from openai import OpenAI
    client = OpenAI(api_key=api_key)
    # GPT-5.x models require max_completion_tokens; older models accept both
    tokens_kwarg = "max_completion_tokens" if model_id.startswith("gpt-5") else "max_tokens"
    response = client.chat.completions.create(
        model=model_id,
        messages=_system_messages("openai") + [{"role": "user", "content": prompt}],
        temperature=temperature,
        **{tokens_kwarg: 1500},
    )
    return response.choices[0].message.content.strip()


def generate_claude(api_key: str, model_id: str, prompt: str, temperature: float) -> str:
    import anthropic
    client = anthropic.Anthropic(api_key=api_key)
    message = client.messages.create(
        model=model_id,
        max_tokens=1500,
        temperature=temperature,
        system="You are a careful academic writing assistant.",
        messages=[{"role": "user", "content": prompt}],
    )
    return message.content[0].text.strip()


def generate_gemini(api_key: str, model_id: str, prompt: str, temperature: float) -> str:
    from google import genai
    from google.genai import types
    client = genai.Client(api_key=api_key)
    response = client.models.generate_content(
        model=model_id,
        contents=f"You are a careful academic writing assistant.\n\n{prompt}",
        config=types.GenerateContentConfig(
            temperature=temperature,
            max_output_tokens=1500,
        ),
    )
    return response.text.strip()


def generate_nvidia(api_key: str, model_id: str, prompt: str, temperature: float, thinking: bool) -> str:
    messages = [
        {"role": "system", "content": "You are a careful academic writing assistant."},
        {"role": "user", "content": prompt},
    ]
    payload: dict = {
        "model": model_id,
        "messages": messages,
        "max_tokens": 1500,
        "temperature": temperature,
        "top_p": 1.0,
        "stream": True,
    }
    if thinking:
        payload["chat_template_kwargs"] = {"thinking": True}

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Accept": "text/event-stream",
    }

    response = requests.post(NVIDIA_API_URL, headers=headers, json=payload, stream=True)
    response.raise_for_status()

    chunks: list[str] = []
    for raw_line in response.iter_lines():
        if not raw_line:
            continue
        line = raw_line.decode("utf-8")
        if line.startswith("data:"):
            data_str = line[len("data:"):].strip()
            if data_str == "[DONE]":
                break
            try:
                data = json.loads(data_str)
                delta = data["choices"][0].get("delta", {})
                content = delta.get("content") or ""
                chunks.append(content)
            except (json.JSONDecodeError, KeyError, IndexError):
                continue

    return "".join(chunks).strip()



# ---------------------------------------------------------------------------
# Main layout
# ---------------------------------------------------------------------------

left_col, right_col = st.columns([1.4, 0.85])

with left_col:
    # ── Instruction prompt ───────────────────────────────────────────────────
    st.markdown('<div class="section-label">Instruction Prompt</div>', unsafe_allow_html=True)
    instruction_prompt = st.text_area(
        "Instruction for the model",
        value=DEFAULT_INSTRUCTION,
        height=140,
        label_visibility="collapsed",
        help="Combined with your answers and sent to the model.",
    )

    st.markdown("---")

    # ── Question picker ──────────────────────────────────────────────────────
    st.markdown('<div class="section-label">Research Intake β€” Pick a Question & Answer It</div>', unsafe_allow_html=True)

    # Move selector displayed as styled headers
    MOVE_CLASSES = ["m1", "m2", "m3"]
    move_cols = st.columns(3)
    for col, (move_label, cls) in zip(move_cols, zip(MOVE_LABELS, MOVE_CLASSES)):
        icon = MOVE_ICONS[move_label]
        subtitle = MOVE_SUBTITLES[move_label]
        title_part = move_label.split("–")[0].strip()
        name_part = move_label.split("–")[1].strip() if "–" in move_label else ""
        col.markdown(
            f'<div class="move-header {cls}">'
            f'  <div class="move-icon">{icon}</div>'
            f'  <div>'
            f'    <p class="move-title">{title_part}</p>'
            f'    <p class="move-subtitle">{name_part}</p>'
            f'    <p class="move-subtitle" style="font-style:italic;">{subtitle}</p>'
            f'  </div>'
            f'</div>',
            unsafe_allow_html=True,
        )

    selected_move_label = st.selectbox(
        "Select Move",
        MOVE_LABELS,
        format_func=lambda m: f"{MOVE_ICONS[m]}  {m}",
        key="move_selector",
    )

    move_questions = MOVES[selected_move_label]
    selected_question = st.selectbox(
        "Select question",
        move_questions,
        key="question_selector",
    )

    current_answer = st.text_area(
        "Your answer",
        height=110,
        key="current_answer",
        placeholder="Type your answer here…",
        label_visibility="visible",
    )

    add_col, clear_col = st.columns([1, 1])
    with add_col:
        if st.button("βž•  Add answer", use_container_width=True):
            if not current_answer.strip():
                st.warning("Please type an answer before adding.")
            else:
                st.session_state["qa_pairs"].append({
                    "move": selected_move_label,
                    "question": selected_question,
                    "answer": current_answer.strip(),
                })
                st.rerun()
    with clear_col:
        if st.button("πŸ—‘  Clear all", use_container_width=True):
            st.session_state["qa_pairs"] = []
            st.rerun()

    st.markdown("---")

    # ── Collected answers ────────────────────────────────────────────────────
    qa_pairs: list[dict] = st.session_state["qa_pairs"]

    if qa_pairs:
        # Group by move for display
        from collections import defaultdict
        grouped: dict[str, list[tuple[int, dict]]] = defaultdict(list)
        for idx, pair in enumerate(qa_pairs):
            grouped[pair["move"]].append((idx, pair))

        for move_label, cls in zip(MOVE_LABELS, MOVE_CLASSES):
            pairs_in_move = grouped.get(move_label, [])
            if not pairs_in_move:
                continue
            icon = MOVE_ICONS[move_label]
            title_part = move_label.split("–")[0].strip()
            st.markdown(
                f'<div class="move-header {cls}" style="margin-bottom:0.3rem;">'
                f'  <div class="move-icon" style="font-size:1.2rem;">{icon}</div>'
                f'  <p class="move-title" style="margin:0;">{title_part} β€” {len(pairs_in_move)} answer(s)</p>'
                f'</div>',
                unsafe_allow_html=True,
            )
            for idx, pair in pairs_in_move:
                col_text, col_btn = st.columns([11, 1])
                with col_text:
                    st.markdown(
                        f'<div class="qa-item">'
                        f'  <div class="qa-q">{pair["question"]}</div>'
                        f'  <div class="qa-a">{pair["answer"]}</div>'
                        f'</div>',
                        unsafe_allow_html=True,
                    )
                with col_btn:
                    if st.button("βœ•", key=f"rm_{idx}", help="Remove"):
                        st.session_state["qa_pairs"].pop(idx)
                        st.rerun()
    else:
        st.info("No answers yet β€” pick a question above, type your answer, and click **βž• Add answer**.")

    st.markdown("---")
    generate_clicked = st.button("✨  Build introduction", use_container_width=True, type="primary")


# ── Right panel ─────────────────────────────────────────────────────────────
with right_col:
    st.markdown('<div class="section-label">How it works</div>', unsafe_allow_html=True)
    st.markdown(
        "<div class='subtle-card'>"
        "<b>1.</b> Choose a Move header, then pick a question from the dropdown.<br><br>"
        "<b>2.</b> Type your answer and click <em>βž• Add answer</em>.<br><br>"
        "<b>3.</b> Repeat across all three Moves for the best introduction.<br><br>"
        "<b>4.</b> Click <em>✨ Build introduction</em>.<br><br>"
        "The app merges the instruction prompt + all your answers into one structured prompt "
        "and calls the selected model."
        "</div>",
        unsafe_allow_html=True,
    )

    st.markdown("---")
    st.markdown('<div class="section-label">Active Model</div>', unsafe_allow_html=True)
    if backend == "ChatGPT (OpenAI)":
        st.info(f"🟒  {selected_openai_model}")
    elif backend == "Claude (Anthropic)":
        st.info(f"🟠  {selected_claude_model}")
    elif backend == "Gemini (Google)":
        st.info(f"πŸ”΅  {selected_gemini_model}")
    elif backend == "NVIDIA":
        st.info(f"🟣  {selected_nvidia_model}")

    # Move coverage
    if qa_pairs:
        st.markdown("---")
        st.markdown('<div class="section-label">Move Coverage</div>', unsafe_allow_html=True)
        for move_label, cls in zip(MOVE_LABELS, MOVE_CLASSES):
            count = sum(1 for p in qa_pairs if p["move"] == move_label)
            icon = "βœ…" if count else "β—‹"
            short = move_label.split("–")[0].strip()
            st.markdown(f"{icon} **{short}** β€” {count} answer(s)")


# ---------------------------------------------------------------------------
# Generation
# ---------------------------------------------------------------------------

if generate_clicked:
    missing_key = False
    if backend == "ChatGPT (OpenAI)" and not openai_api_key.strip() and not FALLBACK_OPENAI_API_KEY:
        st.error("Please enter your OpenAI API key in the sidebar.")
        missing_key = True
    elif backend == "Claude (Anthropic)" and not claude_api_key.strip():
        st.error("Please enter your Anthropic API key in the sidebar.")
        missing_key = True
    elif backend == "Gemini (Google)" and not gemini_api_key.strip():
        st.error("Please enter your Google AI API key in the sidebar.")
        missing_key = True
    elif backend == "NVIDIA" and not nvidia_api_key.strip():
        st.error("Please enter your NVIDIA API key in the sidebar.")
        missing_key = True

    if not instruction_prompt.strip():
        st.error("Please provide an instruction prompt.")
    elif not qa_pairs:
        st.error("Please add at least one answered question.")
    elif not missing_key:
        prompt = build_research_prompt(instruction_prompt, qa_pairs)
        with st.expander("Show assembled prompt", expanded=False):
            st.code(prompt, language="text")

        try:
            with st.status("Crafting introduction…", expanded=True) as status:
                if backend == "ChatGPT (OpenAI)":
                    status.write(f"Calling {selected_openai_model} via OpenAI API…")
                    introduction = generate_openai(
                        (openai_api_key.strip() or FALLBACK_OPENAI_API_KEY), OPENAI_MODELS[selected_openai_model], prompt, temperature
                    )
                elif backend == "Claude (Anthropic)":
                    status.write(f"Calling {selected_claude_model} via Anthropic API…")
                    introduction = generate_claude(
                        claude_api_key.strip(), CLAUDE_MODELS[selected_claude_model], prompt, temperature
                    )
                elif backend == "Gemini (Google)":
                    status.write(f"Calling {selected_gemini_model} via Google AI API…")
                    introduction = generate_gemini(
                        gemini_api_key.strip(), GEMINI_MODELS[selected_gemini_model], prompt, temperature
                    )
                elif backend == "NVIDIA":
                    status.write(f"Calling {selected_nvidia_model} via NVIDIA API (streaming)…")
                    introduction = generate_nvidia(
                        nvidia_api_key.strip(), NVIDIA_MODELS[selected_nvidia_model],
                        prompt, temperature, nvidia_thinking
                    )
                status.update(label="Introduction ready", state="complete")
        except Exception as error:
            st.exception(error)
        else:
            st.markdown('<div class="section-label">Crafted Introduction</div>', unsafe_allow_html=True)
            st.text_area("Output", value=introduction, height=450, label_visibility="collapsed")
            st.session_state["last_output"] = introduction
            st.session_state["last_prompt"] = prompt
            st.success("Done!")
else:
    if "last_output" in st.session_state:
        st.markdown('<div class="section-label">Most Recent Output</div>', unsafe_allow_html=True)
        st.text_area("Output", value=st.session_state["last_output"], height=450, label_visibility="collapsed")
        with st.expander("Show last assembled prompt", expanded=False):
            st.code(st.session_state.get("last_prompt", ""), language="text")