File size: 19,560 Bytes
14aed0a
44a6389
 
 
 
93b0432
44a6389
93b0432
44a6389
 
 
 
75cabef
0d61090
14aed0a
c4f2fd0
ead8a19
c4f2fd0
674c314
0d61090
 
bdd7351
0d61090
 
 
 
 
f19dd5d
 
 
 
 
25aa3a4
0d61090
e2767e1
0d61090
25aa3a4
0d61090
 
 
44a6389
0d61090
 
 
 
 
 
 
bdd7351
0d61090
 
 
 
bdd7351
 
0d61090
 
93b0432
275e8cc
0d61090
44a6389
0d61090
 
44a6389
 
0d61090
44a6389
93b0432
44a6389
929528a
 
 
 
44a6389
25aa3a4
 
 
1d32a2a
fb72c6e
25aa3a4
fb72c6e
 
25aa3a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c3f3c1
 
 
 
 
 
 
 
 
 
bdd7351
a97666f
bdd7351
 
 
 
 
 
 
 
1190904
 
 
bdd7351
 
1190904
bdd7351
 
 
 
 
 
 
ae5b61f
 
 
bdd7351
 
 
 
 
 
2fd742b
 
 
 
 
 
 
 
bdd7351
 
10ed3ea
 
 
 
bdd7351
10ed3ea
bdd7351
 
 
 
 
10ed3ea
 
 
 
 
 
 
 
 
ed8ff60
 
 
 
 
 
 
 
 
 
 
 
c4f2fd0
bdd7351
f19dd5d
4b161e3
bdd7351
 
8addac0
8cdc72b
bdd7351
6610dfb
08a16da
8addac0
08a16da
bdd7351
 
 
 
4b161e3
c4f2fd0
4b161e3
 
c4f2fd0
 
 
4b161e3
c4f2fd0
4b161e3
 
 
 
 
25aa3a4
4b161e3
 
 
 
bdd7351
4b161e3
bdd7351
 
 
 
b4132e2
4b161e3
 
 
 
c4f2fd0
4b161e3
 
 
c4f2fd0
 
4b161e3
44a6389
1d32a2a
0d61090
fb72c6e
38244ab
93b0432
ead8a19
 
 
 
25aa3a4
17aa476
44a6389
17aa476
93b0432
44a6389
ead8a19
 
 
81c2708
25aa3a4
 
0d61090
93b0432
 
44a6389
 
93b0432
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eac4a77
 
81c2708
93b0432
81c2708
 
22e24d8
44a6389
93b0432
 
eac4a77
0d61090
93b0432
 
22e24d8
 
 
93b0432
 
eac4a77
 
93b0432
 
44a6389
 
9c3f3c1
0d61090
 
9c3f3c1
0d61090
 
 
 
 
 
 
 
9c3f3c1
 
 
0d61090
 
 
 
 
 
 
 
44a6389
 
c4f2fd0
f19dd5d
44a6389
c4f2fd0
 
44a6389
c4f2fd0
0d61090
 
44a6389
0d61090
44a6389
 
0d61090
44a6389
 
 
 
 
 
 
 
9c3f3c1
44a6389
c4f2fd0
44a6389
5dbfc81
44a6389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69cadaf
889972e
4fe244a
5aa1009
 
 
4fe244a
 
ae5b61f
69cadaf
 
 
 
5aa1009
69cadaf
 
 
 
 
4fe244a
 
69cadaf
 
 
 
 
 
 
 
 
4fe244a
ee2403a
95a9446
 
7bc8411
95a9446
 
 
7bc8411
 
ee2403a
95a9446
4fe244a
 
 
 
 
 
95a9446
4fe244a
 
95a9446
 
 
2ba736b
c54c10b
889972e
c4f2fd0
 
889972e
 
4fe244a
0d61090
06c5b81
4b161e3
 
 
 
69cadaf
a423f23
c54c10b
889972e
0d61090
 
4fe244a
 
c54c10b
889972e
 
 
 
69cadaf
889972e
5528342
c54c10b
 
 
f19dd5d
c54c10b
 
 
5528342
 
c54c10b
95a9446
c4f2fd0
d1fb859
5528342
d1fb859
5528342
0d61090
 
5528342
 
 
 
 
 
 
d1fb859
71c4760
 
 
7bc8411
c4f2fd0
 
 
 
 
71c4760
4b161e3
 
c4f2fd0
4b161e3
 
 
 
 
c4f2fd0
4b161e3
 
 
c4f2fd0
 
2ba736b
4b161e3
c54c10b
 
c4f2fd0
 
c54c10b
 
c4f2fd0
 
 
 
 
9c30cfa
95a9446
358ea45
 
 
 
7bc8411
629c735
9c30cfa
c4f2fd0
44a6389
0d61090
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
import spaces
from langchain_ollama import OllamaLLM
from langchain_core.prompts import ChatPromptTemplate
import faiss
import pandas as pd
import torch
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer, AutoModelForCausalLM
import gradio as gr
import os
import json
import uuid
from datetime import datetime, timezone
from pymongo import MongoClient

import time
import random
SESSION_LIMIT_SECONDS = 300
MONGODB_URI = os.getenv("MONGODB_URI") 
MONGODB_DB = os.getenv("MONGODB_DB", "chatbot_db") 
MONGODB_COLLECTION = os.getenv("MONGODB_COLLECTION", "chat_logs") 
COUNTS_DOC_TITLE = "support_type_counts"
 

mongo_client = None 
mongo_collection = None 
 
def get_session_id(session_id, request: gr.Request):
    if session_id:
        return session_id
    return request.session_hash or str(uuid.uuid4())


def init_mongo(): 
    global mongo_client, mongo_collection, mongo_counts_collection
 

    if mongo_collection is not None: 
        return 
 

    if not MONGODB_URI: 
        raise ValueError("MONGODB_URI is not set in Space secrets.") 
 

    mongo_client = MongoClient(MONGODB_URI) 
    db = mongo_client[MONGODB_DB] 
    mongo_collection = db[MONGODB_COLLECTION] 
    mongo_counts_collection = db["study_counts"]  
 

    # useful for avoiding duplicate session ids 
    mongo_collection.create_index("session_id", unique=True) 
    mongo_counts_collection.create_index("title", unique=True)
    

# embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
MODEL_ID = "meta-llama/Meta-Llama-3.1-8B-Instruct"
LOG_DIR = "/data/chat_logs"
# os.makedirs(LOG_DIR, exist_ok =True)

# index = faiss.read_index("empathetic_rag_index.faiss")
# chunks_df = pd.read_json("empathetic_rag_chunks.json")

# Convert retrieved rows to list for easy lookup
# rag_texts = chunks_df["rag_text"].tolist()


MODE_INSTRUCTIONS = {
    "Emotional: Responds with empathy, comfort, and understanding": "You are an Emotional Support Agent focused on empathy, comfort, and attentive listening to help users process feelings. Communicate warmly, gently, and without judgment, creating a safe space. Validate emotions in context, prioritize listening over solving, and remain transparent as an AI. Encourage gentle elaboration and prioritize emotional validation and psychological safety.", 
    "Informational: Gives practical advice and helpful information": "You are an Informational Support Agent providing factual, practical, and actionable guidance to resolve problems efficiently. Communicate clearly, objectively, and concisely, with brief empathy before solutions. Base responses on verifiable information and best practices, correct misconceptions, state limitations or need for professional help, and avoid empty reassurance or false experience.", 
    "Esteem: Encourages you and affirms your strengths": "You are an Esteem Support Agent focused on building confidence and self-worth. Communicate in an uplifting, sincere, and empowering way. Highlight strengths, effort, resilience, and progress from user input, reframe self-doubt constructively, and emphasize growth and effort over perfection or innate ability.", 
    "Social Network: Helps you feel connected and supported by others": "You are a Social Network Support Agent focused on reducing isolation and fostering belonging through community and shared connections. Communicate inclusively and clearly. Normalize experiences, suggest relevant groups or networks, and guide users toward actionable social engagement and peer interaction." 
}
model =None
tokenizer =None
device =None

def initModel():
    global model, device, tokenizer
    if model is not None and tokenizer is not None and device is not None:
         return
    device = "cuda" if torch.cuda.is_available() else "cpu" 
    dtype = torch.float16 if device == "cuda" else torch.float32 
    tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) 
    model = AutoModelForCausalLM.from_pretrained( 
        MODEL_ID, 
        dtype=dtype
    )
    model.to(device) 
    model.eval() 
    print(device)
    model.config.pad_token_id = tokenizer.pad_token_id 
    model.generation_config.pad_token_id = tokenizer.pad_token_id 
    model.config.eos_token_id = tokenizer.eos_token_id 
    model.generation_config.eos_token_id = tokenizer.eos_token_id 
    
def get_request_metadata(request: gr.Request):
    headers = dict(request.headers) if request and request.headers else {}
    referer = headers.get("referer") or headers.get("Referer")
    session_hash = request.session_hash if request else None
    query_params = dict(request.query_params) if request and request.query_params else {}
    return {
        "referer": referer,
        "session_hash": session_hash,
        "query_params": query_params
    }
def get_c_value(session_id, request: gr.Request):
    return request.query_params.get("c", "0"),request.query_params.get("session_hash",session_id)


def assign_support_type_from_counts():
    doc = get_counts_doc()

    customization = doc.get("customization", {})
    non_customization = doc.get("non_customization", {})

    all_types = list(MODE_INSTRUCTIONS.keys())
    # print("custom...........................", type(customization),customization)
    # print("nc",type(non_customization),non_customization)
    gaps = {}
    for support_type in all_types:
        # print("support",support_type)
        custom_count = customization.get(support_type, 0)
        noncustom_count = non_customization.get(support_type, 0)
        gaps[support_type] = custom_count - noncustom_count

    max_gap = max(gaps.values())
    candidates = [k for k, v in gaps.items() if v == max_gap]

    return random.choice(candidates)


def get_counts_doc():
    init_mongo()
    doc = mongo_counts_collection.find_one({"title": COUNTS_DOC_TITLE})
    if not doc:
        raise ValueError("Counts document not found. Please create it manually.")
    return doc

def has_assignment_been_counted(session_id):
    init_mongo()
    doc = mongo_collection.find_one(
        {"session_id": session_id},
        {"_id": 0, "count_recorded": 1}
    )
    return bool(doc and doc.get("count_recorded"))
def increment_support_type_count(condition_key, support_type, session_id):
    init_mongo()
    print("increment_support_type_count called")
    print("condition_key:", condition_key)
    print("support_type:", support_type)
    print("session_id:", session_id)

    result = mongo_counts_collection.update_one(
        {"title": COUNTS_DOC_TITLE},
        {
            "$inc": {f"{condition_key}.{support_type}": 1},
            "$addToSet": {f"sessions.{condition_key}.{support_type}": session_id}
        }
    )

    print("matched_count:", result.matched_count)
    print("modified_count:", result.modified_count)

    doc = mongo_counts_collection.find_one({"title": COUNTS_DOC_TITLE})
    print("updated doc:", doc)

    
def mark_assignment_counted(session_id, assigned_condition):
    init_mongo()
    mongo_collection.update_one(
        {"session_id": session_id},
        {
            "$set": {
                "count_recorded": True,
                "assigned_condition": assigned_condition
            }
        },
        upsert=True
    )
def start_chat(initial_issue, chat_history, context, support_type, session_id, start_time, request: gr.Request): 

    session_id = get_session_id(session_id, request)
    initial_issue = (initial_issue or "").strip() 

    c_value, sid = get_c_value(session_id, request)
    # print(".............................................................................................................",type(c_value),c_value)
    if c_value == "0" or c_value == 0:
        if not support_type:
            support_type = assign_support_type_from_counts()
        condition_key = "non_customization"
    else:
        condition_key = "customization"



    if not initial_issue or (c_value == "1" and not support_type):
        return ( 
            chat_history, context, chat_history, session_id, start_time,
            gr.update(),                      # initial textbox 
            gr.update(),                      # radio 
            gr.update(value="", interactive=False),    # user_input
            gr.update(interactive=True),               # start_btn
            gr.update(interactive=False)               # send_btn
        ) 
    start_time = time.time()
    opening_response = ( 
        f"Oh, you need help with this situation: {initial_issue}. " 
        f"Could you say more?" 
    ) 


    chat_history = chat_history + [ 
        {"role": "user", "content": initial_issue}, 
        {"role": "assistant", "content": opening_response} 
    ] 
    
    context += f"\nUser: {initial_issue}\nAI: {opening_response}" 

    if not has_assignment_been_counted(session_id):
        increment_support_type_count(condition_key, support_type, sid)
        mark_assignment_counted(session_id, condition_key)
    save_chat_log(session_id, support_type, chat_history, context,request) 
    return ( 
        chat_history, 
        context, 
        chat_history, 
        session_id, start_time,
        gr.update(value=initial_issue, interactive=False),   # lock initial textbox 
        gr.update(value=support_type, interactive=False),    # lock radio 
        gr.update(value="", interactive=True),               # enable followup textbox 
        gr.update(interactive=False),                         # disable start button 
        gr.update(interactive=False)                        # send still disabled until typing
    ) 

@spaces.GPU()
def generate_response(context, question, support_type, support_instruction): 
        initModel()
        print("model", next(model.parameters()))
        system_prompt = f"""
        You are an emotional or interpersonal support assistant. 
        You must NOT answer unrelated to emotional or interpersonal support  questions such as coding, math, general trivia, shopping, politics, entertainment, random factual questions, technical help, anything outside mental health support. 
        If the user asks something unrelated to emotional or interpersonal support, politely say: 
        "I'm here specifically to support interpersonal or wellbeing-related concerns. Could you share more about what's bothering you?" 

        Selected support mode: {support_type}

        Mode definition:
        {support_instruction}

        Do not diagnose medical or psychiatric conditions. Be conversational, supportive, and concise. Do not provide medical advice. 

        If user mentions immediate danger or self-harm, encourage reaching out to a trusted person or emergency professional support. 
        Keep responses conversational and not overly long.
        """
        user_prompt = f"""
   
        Conversation history:
        {context}


        User question:
        {question}


        Answer:
        """
        messages = [ 
        {"role": "system", "content": system_prompt.strip()}, 
        {"role": "user", "content": user_prompt.strip()} 
        ] 
 
        inputs = tokenizer.apply_chat_template( 
                messages, 
                tokenize=True, 
                add_generation_prompt=True, 
                return_tensors="pt",
                return_dict=True
            )
        
        input_device = next(model.parameters()).device
        inputs = {k: v.to(input_device) for k, v in inputs.items()}
        

        with torch.no_grad(): 
                outputs = model.generate( 
                    **inputs, 
                    max_new_tokens=250, 
                    do_sample=True, 
                    temperature=0.6, 
                    top_p=0.9,
                    pad_token_id=tokenizer.pad_token_id, 
                    eos_token_id=tokenizer.eos_token_id 
                ) 
        
        input_len = inputs["input_ids"].shape[1]
        response_tokens = outputs[0][input_len:] 
        result = tokenizer.decode(response_tokens, skip_special_tokens=True).strip() 
        return result


def save_chat_log(session_id, support_type, chat_history, context, request: gr.Request): 
    init_mongo() 
    now = datetime.now(timezone.utc).isoformat() 
    metadata = get_request_metadata(request)
    mongo_collection.update_one( 
        {"session_id": session_id}, 
        { 
            "$set": { 
                "support_type": support_type, 
                "updated_at": now, 
                "context": context, 
                "chat_history": chat_history, 
                "referer": metadata["referer"],
                "request_session_hash": metadata["session_hash"],
                "request_query_params": metadata["query_params"],
            }, 
            "$setOnInsert": { 
                "session_id": session_id, 
                "created_at": now, 
            } 
        }, 
        upsert=True 
    ) 


def chat_fn(user_input, chat_history, context, support_type, session_id, start_time,  request: gr.Request): 
    session_id = get_session_id(session_id, request)
    user_input = (user_input or "").strip() 
    if start_time is not None and (time.time() - start_time) >= SESSION_LIMIT_SECONDS:
        return "", chat_history, context, chat_history, session_id, start_time, gr.update(interactive=False)
    if not user_input: 
         return "", chat_history, context, chat_history, session_id,start_time, gr.update(interactive=False)
    gr.Radio(interactive=False, value=support_type)
    # retrieved_context = retrieve_context(user_input, top_k=3) 
    support_instruction = MODE_INSTRUCTIONS.get( 
        support_type
    ) 

    result = generate_response(context, user_input, support_type,  support_instruction ) 

 
    chat_history = chat_history + [ 
        {"role": "user", "content": user_input}, 
        {"role": "assistant", "content": result} 
    ] 
  
    context += f"\nUser: {user_input}\nAI: {result}" 
    save_chat_log(session_id, support_type, chat_history, context,request) 
 
    return "", chat_history, context, chat_history, session_id, start_time, gr.update(interactive=False)
 

custom_css = """ 
/* Hide all chatbot message action areas entirely */ 
.message-actions { 
    display: none !important; 
} 
.chatbot .message-actions { 
   display: none !important; 
} 
[data-testid="chatbot"] .message-actions { 
    display: none !important; 
} 
/* Hide icon wrappers/buttons if your version uses them */ 
.icon-button-wrapper, 
.icon-button, 
button[aria-label="Copy"], 
button[aria-label="Delete"], 
button[aria-label="Retry"], 
button[aria-label="Undo"], 
button[aria-label="Copy all"] { 
    display: none !important; 
} 
/* Hide footer/action rows that remain empty in some versions */ 
[data-testid="chatbot"] footer, 
[data-testid="chatbot"] .footer, 
[data-testid="chatbot"] .actions, 
[data-testid="chatbot"] .buttons { 
    display: none !important; 
} 

""" 

def init_support_choices(request: gr.Request):
    c_value = request.query_params.get("c", "1")
    rng = random.Random(request.session_hash)
    choices = list(MODE_INSTRUCTIONS.keys())
    rng.shuffle(choices)
    if c_value == "0":
        assigned_type = assign_support_type_from_counts()
        print("..............................................................................................................")
        print(assigned_type, assigned_type in list(MODE_INSTRUCTIONS.keys()))
        return (
            [],
            gr.update(
                choices=choices,
                value=assigned_type,
                visible=False,
                interactive=False
            ),
            gr.update(visible=False)
        )

    return (
        choices,
        gr.update(
            choices=choices,
            value=None,
            visible=True,
            interactive=True
        ),
        gr.update(visible=True)
    )

def disable_after_timeout(start_time):
    if start_time is None:
        return gr.update()
    remaining = max(0, int(SESSION_LIMIT_SECONDS - (time.time() - start_time)))
    expired = remaining <= 0
    if expired:
        return gr.update(interactive=False)
    return gr.update(interactive=True)
 

def toggle_start_button(initial_issue, support_type, request: gr.Request):
    c_value = request.query_params.get("c", "1")

    if c_value == "0":
        ready = bool((initial_issue or "").strip())
    else:
        ready = bool((initial_issue or "").strip()) and bool(support_type)

    return gr.update(interactive=ready)
def toggle_send_button(user_input):
        ready = bool((user_input or "").strip())
        return gr.update(interactive=ready)

with gr.Blocks() as demo: 
    
    start_time_state = gr.State(None)
    timer = gr.Timer(1.0)

    support_choices_state = gr.State([])

    # gr.Markdown("## Support Chatbot") 
    gr.Markdown("Describe a real-life personal problem or stressful situation you are currently experiencing and would like support with.") 
    initial_issue = gr.Textbox( 
        label="Briefly describe why you need help", 
        placeholder="Type the situation first" 
    ) 
    support_type_text = gr.Markdown("Please choose one support type for your chat session.") 

    support_type = gr.Radio( 
        choices=[],
        # value="Emotional", 
        label="Support type",
        interactive=True,
        visible=True
    ) 

    demo.load(
        init_support_choices,
        inputs=None,
        outputs=[support_choices_state, support_type, support_type_text]
    )
    start_btn = gr.Button("Start", interactive=False)
    chatbot = gr.Chatbot(label="Chat") 
    history_state = gr.State([]) 
    context_state = gr.State("") 
    session_state = gr.State("") 

    user_input = gr.Textbox( 
        label="Your message", 
        placeholder="Describe a stressful situation you need suggestions for",
        interactive = False
    ) 


    initial_issue.input(
        toggle_start_button,
        inputs=[initial_issue, support_type],
        outputs=[start_btn],
        queue=False
    )

    support_type.change(
        toggle_start_button,
        inputs=[initial_issue, support_type],
        outputs=[start_btn],
        queue=False
    )   


    with gr.Row(): 
        send_btn = gr.Button("Send", interactive=False) 
    # time_left_text = gr.Markdown("")
    user_input.input(
        toggle_send_button,
        inputs=[user_input],
        outputs=[send_btn],
        queue=False
    )    
    start_btn.click( 
        start_chat, 
        inputs=[initial_issue, history_state, context_state, support_type, session_state, start_time_state], 
        outputs=[ 
            chatbot, 
            context_state, 
            history_state, 
            session_state, 
            start_time_state,
            initial_issue, 
            support_type, 
            user_input, 
            start_btn,
            send_btn
        ]
    ) 
    send_btn.click( 
        chat_fn, 
        inputs=[user_input, history_state, context_state, support_type, session_state, start_time_state], 
        outputs=[user_input, chatbot, context_state, history_state, session_state, start_time_state, send_btn]
    ) 

    user_input.submit(
        chat_fn,
        inputs=[user_input, history_state, context_state, support_type, session_state, start_time_state],
        outputs=[user_input, chatbot, context_state, history_state, session_state, start_time_state, send_btn]
    )

   

    timer.tick(
            disable_after_timeout,
            inputs=[start_time_state],
            outputs=[send_btn]
        )

demo.launch(css=custom_css)