Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- app.py +160 -0
- requirements.txt +10 -0
app.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""chatbot.ipynb
|
3 |
+
|
4 |
+
Automatically generated by Colaboratory.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1zgihAeNpcDd0opNPsbnmS2UNgz0rsfOB
|
8 |
+
"""
|
9 |
+
|
10 |
+
from langchain.text_splitter import CharacterTextSplitter
|
11 |
+
from langchain_community.document_loaders import PyPDFLoader
|
12 |
+
|
13 |
+
import logging
|
14 |
+
import sys
|
15 |
+
|
16 |
+
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
|
17 |
+
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
|
18 |
+
|
19 |
+
from llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext
|
20 |
+
from llama_index.llms import HuggingFaceLLM
|
21 |
+
from langchain.document_loaders import PyPDFLoader
|
22 |
+
|
23 |
+
documents = SimpleDirectoryReader("Dat").load_data()
|
24 |
+
|
25 |
+
from llama_index.prompts.prompts import SimpleInputPrompt
|
26 |
+
|
27 |
+
|
28 |
+
system_prompt = """Emphasize empathy and active listening: Create a safe space for users to share their thoughts and feelings without judgment.
|
29 |
+
Focus on understanding and validation: Reflect back user emotions and experiences to demonstrate understanding and build trust.
|
30 |
+
Offer evidence-based support: Provide grounding techniques, coping strategies, and psychoeducation based on sound mental health principles.
|
31 |
+
Personalize responses: Tailor interactions to individual needs, preferences, and goals.
|
32 |
+
Maintain ethical boundaries: Respect user privacy, confidentiality, and autonomy.
|
33 |
+
Recognize limitations: Acknowledge that the chatbot is not a replacement for professional therapy and encourage seeking licensed help when needed.
|
34 |
+
Key goals:
|
35 |
+
|
36 |
+
Reduce symptoms of anxiety, depression, and stress.
|
37 |
+
Improve emotional regulation and coping skills.
|
38 |
+
Enhance self-awareness and self-compassion.
|
39 |
+
Promote healthy relationships and communication.
|
40 |
+
Build resilience and problem-solving skills.
|
41 |
+
Encourage positive self-care and lifestyle choices.
|
42 |
+
Specific prompts:
|
43 |
+
|
44 |
+
"Greet the user warmly and introduce yourself as their AI therapist."
|
45 |
+
"Ask open-ended questions to elicit user thoughts, feelings, and concerns."
|
46 |
+
"Respond empathetically to user disclosures, validating their experiences."
|
47 |
+
"Offer appropriate mental health resources, exercises, or techniques based on user needs."
|
48 |
+
"Guide users through mindfulness exercises or relaxation techniques."
|
49 |
+
"Challenge negative thinking patterns and encourage cognitive reframing."
|
50 |
+
"Help users set realistic goals and track progress towards mental wellness."
|
51 |
+
"Provide psychoeducation on various mental health topics and treatment options."
|
52 |
+
"Conclude sessions with positive affirmations and encouragement."
|
53 |
+
"Remind users of the chatbot's limitations and the importance of seeking professional help."
|
54 |
+
"Always prioritize user safety and offer crisis resources in case of urgent needs."
|
55 |
+
Additional considerations:
|
56 |
+
|
57 |
+
Tailor prompts to specific mental health conditions or challenges.
|
58 |
+
Incorporate humor or lightheartedness when appropriate to build rapport.
|
59 |
+
Provide options for different communication styles (e.g., text, voice, interactive activities).
|
60 |
+
Continuously monitor and refine prompts based on user feedback and clinical expertise."""
|
61 |
+
|
62 |
+
|
63 |
+
|
64 |
+
# This will wrap the default prompts that are internal to llama-index
|
65 |
+
query_wrapper_prompt = SimpleInputPrompt("<|USER|>{query_str}<|ASSISTANT|>")
|
66 |
+
|
67 |
+
import torch
|
68 |
+
|
69 |
+
llm = HuggingFaceLLM(
|
70 |
+
context_window=4096,
|
71 |
+
max_new_tokens=256,
|
72 |
+
generate_kwargs={"temperature": 0.5, "do_sample": False},
|
73 |
+
system_prompt=system_prompt,
|
74 |
+
query_wrapper_prompt=query_wrapper_prompt,
|
75 |
+
tokenizer_name="NousResearch/Llama-2-7b-chat-hf",
|
76 |
+
model_name="NousResearch/Llama-2-7b-chat-hf",
|
77 |
+
device_map="auto",
|
78 |
+
# uncomment this if using CUDA to reduce memory usage
|
79 |
+
model_kwargs={"torch_dtype": torch.float16 })
|
80 |
+
|
81 |
+
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
|
82 |
+
from llama_index.embeddings.langchain import LangchainEmbedding
|
83 |
+
from llama_index import ServiceContext
|
84 |
+
|
85 |
+
embed_model = LangchainEmbedding(
|
86 |
+
HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
|
87 |
+
)
|
88 |
+
|
89 |
+
service_context = ServiceContext.from_defaults(
|
90 |
+
chunk_size=1024,
|
91 |
+
llm=llm,
|
92 |
+
embed_model=embed_model
|
93 |
+
)
|
94 |
+
|
95 |
+
index = VectorStoreIndex.from_documents(documents, service_context=service_context)
|
96 |
+
|
97 |
+
query_engine = index.as_query_engine()
|
98 |
+
response = query_engine.query("What is cyclothymic disorder?")
|
99 |
+
|
100 |
+
print(response)
|
101 |
+
|
102 |
+
import gradio as gr
|
103 |
+
|
104 |
+
def respond_to_user(input_text):
|
105 |
+
response = query_engine.query(input_text)
|
106 |
+
return response
|
107 |
+
|
108 |
+
|
109 |
+
import gradio as gr
|
110 |
+
|
111 |
+
def render_messages():
|
112 |
+
messages = []
|
113 |
+
if hasattr(iface, "_message_history"):
|
114 |
+
for msg in iface._message_history[-3::-1]:
|
115 |
+
messages.append({"role": msg["role"], "content": msg["content"]})
|
116 |
+
|
117 |
+
template = r"""
|
118 |
+
<div class='card'>
|
119 |
+
%for message in messages:
|
120 |
+
{%if message['role'] == 'assistant':%}
|
121 |
+
<div class='card bg-light mb-3' style='max-width: 50rem;'>
|
122 |
+
<div class='card-header'>Assistant</div>
|
123 |
+
<div class='card-body'>{{message['content']}}</div>
|
124 |
+
</div>
|
125 |
+
{%else:%}
|
126 |
+
<div class='card' style='max-width: 50rem;'>
|
127 |
+
<div class='card-header'>User</div>
|
128 |
+
<div class='card-body'>{{message['content']}}</div>
|
129 |
+
</div>
|
130 |
+
{%endif%}
|
131 |
+
%endfor%}
|
132 |
+
</div>
|
133 |
+
"""
|
134 |
+
return gr.outputs.HTML(template)
|
135 |
+
|
136 |
+
def process_inputs(input_text):
|
137 |
+
result = respond_to_user(input_text)
|
138 |
+
iface._message_history.append({"role": "assistant", "content": result})
|
139 |
+
return "", render_messages()
|
140 |
+
|
141 |
+
iface = gr.Interface(fn=process_inputs,
|
142 |
+
inputs=gr.components.Textbox(lines=3, placeholder="Type something..."),
|
143 |
+
outputs=[],
|
144 |
+
title="AI Therapist Chatbot",
|
145 |
+
allow_flagging="never",
|
146 |
+
theme="monochrome",
|
147 |
+
css="""
|
148 |
+
.gradio-container > div:first-child{
|
149 |
+
margin-top: 0 !important;
|
150 |
+
}
|
151 |
+
.gradio-label-container label{
|
152 |
+
font-weight: bold;
|
153 |
+
color: black;
|
154 |
+
}
|
155 |
+
""",
|
156 |
+
article="""
|
157 |
+
Welcome to our AI Therapist chatbot! Feel free to ask anything related to mental health and receive guidance. Confidentiality and privacy notice: Your conversation remains private; we do not store any data.
|
158 |
+
""")
|
159 |
+
|
160 |
+
iface.render()
|
requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
pypdf
|
2 |
+
python-dotenv
|
3 |
+
transformers
|
4 |
+
einops
|
5 |
+
accelerate
|
6 |
+
langchain
|
7 |
+
bitsandbytes
|
8 |
+
sentence_transformers
|
9 |
+
llama-index
|
10 |
+
langchain-community
|