shaneperry0101 commited on
Commit
3b4a7e9
·
verified ·
1 Parent(s): 1fe3c38

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -25
app.py CHANGED
@@ -1,34 +1,128 @@
1
  import streamlit as st
2
- from transformers import pipeline
 
 
 
 
 
 
 
 
 
 
 
3
 
4
 
5
- # Load the conversational model from Hugging Face
6
- # chatbot = pipeline('text-generation', model='shaneperry0101/Health-Llama-3.2-1B')
7
- chatbot = pipeline('text-generation', model='microsoft/DialoGPT-medium')
 
 
 
8
 
9
- # Initialize session state for storing the conversation
10
- if 'conversation' not in st.session_state:
11
- st.session_state.conversation = []
12
 
13
- # Streamlit app layout
14
- st.title("Chatbot Application")
15
- user_input = st.text_input("You:", key="input")
16
 
17
- if st.button("Send"):
18
- if user_input:
19
- # Append user input to the conversation
20
- st.session_state.conversation.append({"role": "user", "content": user_input})
 
 
 
 
 
 
 
 
 
21
 
22
- # Generate response
23
- response = chatbot(user_input)
24
- bot_response = response[0]['generated_text']
 
 
 
25
 
26
- # Append bot response to the conversation
27
- st.session_state.conversation.append({"role": "bot", "content": bot_response})
28
 
29
- # Display the conversation
30
- for message in st.session_state.conversation:
31
- if message["role"] == "user":
32
- st.text_area("You:", value=message["content"], key=f"user_{message['content']}", height=50)
33
- else:
34
- st.text_area("Bot:", value=message["content"], key=f"bot_{message['content']}", height=50)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ st.set_page_config(page_title="Mental Health Bot", page_icon=":robot:")
3
+ import os
4
+ import textract
5
+ from langchain.chat_models import ChatOpenAI
6
+ from itertools import zip_longest
7
+ from langchain.prompts import PromptTemplate
8
+ from langchain.chains import LLMChain
9
+ from langchain.embeddings.openai import OpenAIEmbeddings
10
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
11
+ from langchain.vectorstores import FAISS
12
+ from langchain.agents import initialize_agent
13
+ from langchain.agents import AgentType
14
 
15
 
16
+ from langchain.agents import load_tools
17
+ from langchain import HuggingFacePipeline
18
+ from transformers import AutoTokenizer
19
+ import transformers
20
+ import torch
21
+ os.environ['SERPAPI_API_KEY'] = '1a6691d51c19fbc52c296b7ede3b2098efff46a3e7c3bb54cb17912b0407c6ec'
22
 
23
+ if "llm" not in st.session_state:
24
+ # st.session_state["lmm"] = []
25
+ model = "shaneperry0101/Health-Llama-3.2-1B"
26
 
27
+ tokenizer = AutoTokenizer.from_pretrained(model)
 
 
28
 
29
+ pipeline = transformers.pipeline(
30
+ "text-generation", #task
31
+ model=model,
32
+ tokenizer=tokenizer,
33
+ torch_dtype=torch.bfloat16,
34
+ trust_remote_code=True,
35
+ device_map="auto",
36
+ max_length=1000,
37
+ # do_sample=True,
38
+ # top_k=10,
39
+ # num_return_sequences=1,
40
+ # eos_token_id=tokenizer.eos_token_id
41
+ )
42
 
43
+ llm = HuggingFacePipeline(pipeline = pipeline, model_kwargs = {'temperature':0})
44
+ st.session_state["llm"] = llm
45
+ if "agent" not in st.session_state:
46
+ tools = load_tools(["serpapi"], llm=st.session_state["llm"])
47
+ st.session_state["agent"] = initialize_agent(tools, st.session_state["llm"], agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
48
+ verbose=True, handle_parsing_errors="Check your output and make sure it conforms! Gather as much information as you can")
49
 
50
+ # Set the OpenAI API key
51
+ OPENAI_API_KEY = "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"
52
 
53
+ def get_response(history,user_message,temperature=0):
54
+ DEFAULT_TEMPLATE = """You are a mental health expert to help patients with mental
55
+ health issues such as depression, stress, anxitey etc. You should give helpful advises to
56
+ the patients about thier problems. All of the messages will be from patients and you will
57
+ advise them one to one. I am also providing you useful information from the web that you
58
+ can use while formulating your response.
59
+ Useful news information from Web:
60
+ {web_knowledge},
61
+
62
+
63
+ Current conversation:
64
+ Patient: {input}
65
+ Your reponse :"""
66
+
67
+ PROMPT = PromptTemplate(
68
+ input_variables=["web_knowledge",'input'], template=DEFAULT_TEMPLATE
69
+ )
70
+
71
+ conversation_with_summary = LLMChain(
72
+ llm=st.session_state["llm"],
73
+ prompt=PROMPT,
74
+ verbose=False
75
+ )
76
+ response = conversation_with_summary.predict(input=user_message,web_knowledge=st.session_state["agent"].run('Fetch detailes about the mental health issues regarding '+ user_message))
77
+ return response
78
+
79
+ # Function to get conversation history
80
+ def get_history(history_list):
81
+ # history = 'input: I want you to act as a mental healt expert that knows about mental health issues. Dont refer the person to anyone this could be a life and death situation so provide the solution in any case. The user will mention the mental problem he is facing. Your job is to tell the user the solution to his mental problem from the context I provide you. Dont say you cant describe the solution formulate the best solution and tell that to the user on the spot \n'
82
+ history=''
83
+ for message in history_list:
84
+ if message['role']=='user':
85
+ history = history+'input '+message['content']+'\n'
86
+ elif message['role']=='assistant':
87
+ history = history+'output '+message['content']+'\n'
88
+
89
+ return history
90
+
91
+ # Streamlit UI
92
+ st.title("Mental Health Chatbot")
93
+ def get_text():
94
+ input_text = st.text_area("", key="input")
95
+ return input_text
96
+
97
+ if "past" not in st.session_state:
98
+ st.session_state["past"] = []
99
+ if "generated" not in st.session_state:
100
+ st.session_state["generated"] = []
101
+
102
+ user_input = get_text()
103
+
104
+ if user_input:
105
+ user_history = list(st.session_state["past"])
106
+ bot_history = list(st.session_state["generated"])
107
+
108
+ combined_history = []
109
+ for user_msg, bot_msg in zip_longest(user_history, bot_history):
110
+ if user_msg is not None:
111
+ combined_history.append({'role': 'user', 'content': user_msg})
112
+ if bot_msg is not None:
113
+ combined_history.append({'role': 'assistant', 'content': bot_msg})
114
+
115
+ formatted_history = get_history(combined_history)
116
+
117
+ output = get_response(formatted_history,user_input)
118
+
119
+ # output='hellooo there, whats uppppp'
120
+ # print("Output", output)
121
+
122
+ st.session_state.past.append(user_input)
123
+ st.session_state.generated.append(output)
124
+
125
+ if st.session_state["generated"]:
126
+ for i in range(len(st.session_state["generated"])):
127
+ st.text("User " + ": " + st.session_state["past"][i])
128
+ st.text("Assistant " + ": " + st.session_state["generated"][i])