Adoption commited on
Commit
edbb892
·
verified ·
1 Parent(s): 2253797

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +88 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,90 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from langchain_groq import ChatGroq
3
+ from langchain_community.embeddings import HuggingFaceEmbeddings
4
+ from langchain_community.vectorstores import Chroma
5
+ from langchain.text_splitter import CharacterTextSplitter
6
+ from langchain.chains import ConversationalRetrievalChain
7
+ from langchain.memory import ConversationBufferMemory
8
+ from langchain.schema import SystemMessage
9
 
10
+ # 1. Setup Page
11
+ st.set_page_config(page_title="Serenity AI", page_icon="🌿")
12
+ st.title("🌿 Serenity: Your CBT Companion")
13
+
14
+ # 2. Sidebar - Privacy & Resources
15
+ with st.sidebar:
16
+ st.header("About")
17
+ st.info("This is a support tool, NOT a doctor. Data is processed locally for privacy.")
18
+ groq_api_key = st.text_input("Groq API Key", type="password")
19
+
20
+ # 3. Load & Process Knowledge Base (Only runs once)
21
+ @st.cache_resource
22
+ def setup_rag():
23
+ # Load your manual text file
24
+ with open("cbt_resources.txt", "r") as f:
25
+ raw_text = f.read()
26
+
27
+ # Split into chunks
28
+ text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=50)
29
+ texts = text_splitter.split_text(raw_text)
30
+
31
+ # Create Embeddings (Local & Free)
32
+ embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
33
+
34
+ # Store in Vector DB
35
+ db = Chroma.from_texts(texts, embeddings)
36
+ return db.as_retriever()
37
+
38
+ # 4. Initialize Chat Logic
39
+ if groq_api_key:
40
+ # Setup LLM
41
+ llm = ChatGroq(
42
+ temperature=0.6,
43
+ model_name="llama3-70b-8192",
44
+ groq_api_key=groq_api_key
45
+ )
46
+
47
+ # Setup Memory
48
+ if "memory" not in st.session_state:
49
+ st.session_state.memory = ConversationBufferMemory(
50
+ memory_key="chat_history",
51
+ return_messages=True
52
+ )
53
+
54
+ # Setup RAG Chain
55
+ retriever = setup_rag()
56
+ chain = ConversationalRetrievalChain.from_llm(
57
+ llm=llm,
58
+ retriever=retriever,
59
+ memory=st.session_state.memory,
60
+ verbose=False
61
+ )
62
+
63
+ # Inject System Prompt logic (Simplified for Streamlit)
64
+ # Ideally, you wrap the LLM with the system prompt in the chain creation.
65
+
66
+ # 5. Chat Interface
67
+ if "messages" not in st.session_state:
68
+ st.session_state.messages = [{"role": "assistant", "content": "Hello. I'm Serenity. How are you feeling today?"}]
69
+
70
+ for msg in st.session_state.messages:
71
+ st.chat_message(msg["role"]).write(msg["content"])
72
+
73
+ if prompt := st.chat_input():
74
+ st.session_state.messages.append({"role": "user", "content": prompt})
75
+ st.chat_message("user").write(prompt)
76
+
77
+ # Safety Check (Simple Keyword Filter)
78
+ dangerous_keywords = ["suicide", "kill myself", "end it all"]
79
+ if any(word in prompt.lower() for word in dangerous_keywords):
80
+ response = "I'm really concerned about you, but I am an AI. Please call your local emergency number immediately. You are not alone."
81
+ else:
82
+ # Generate Response using RAG
83
+ response_dict = chain.invoke({"question": prompt})
84
+ response = response_dict['answer']
85
+
86
+ st.session_state.messages.append({"role": "assistant", "content": response})
87
+ st.chat_message("assistant").write(response)
88
+
89
+ else:
90
+ st.warning("Please enter your Groq API Key to start.")