mojiotoo commited on
Commit
ea1c368
·
verified ·
1 Parent(s): 3a72339
chatbot/.streamlit/config.toml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [client]
2
+ showErrorDetails = "none"
3
+
4
+ [theme]
5
+ primaryColor="#ffa7df"
6
+ backgroundColor="#D89ABF"
7
+ secondaryBackgroundColor="#000000"
8
+ textColor="#ffffff"
9
+
chatbot/chatbot.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from langchain_community.chat_models import ChatOllama
3
+ from langchain.schema import HumanMessage, AIMessage
4
+ from langchain.memory import ConversationBufferMemory
5
+ from langchain.chains import LLMChain
6
+ from langchain.prompts import PromptTemplate
7
+
8
+
9
+ # ---- Streamlit Setup ---- #
10
+ st.set_page_config(layout="wide")
11
+ st.markdown(
12
+ "<h1 style='text-align: center; color: inherit;'>⎚-⎚ \nMikeyBot</h1>",
13
+
14
+ unsafe_allow_html=True
15
+ )
16
+ st.markdown(
17
+
18
+ """
19
+ <style>
20
+ .st-emotion-cache-4zpzjl {
21
+ background-color: #bf498f;
22
+ color: #ffffff;
23
+ }
24
+
25
+ .st-emotion-cache-jmw8un{
26
+ background-color: #ffd1ec;
27
+ color: #000000 ;
28
+ }
29
+
30
+ .st-emotion-cache-1k8897g{
31
+ background-color: #d98dba;
32
+ }
33
+
34
+ </style>
35
+ """, unsafe_allow_html=True)
36
+
37
+ # ---- Sidebar Inputs ---- #
38
+ st.sidebar.header("⚙️ Settings")
39
+
40
+ # Dropdown for model selection
41
+ model_options = ["llama3.2", "deepseek-r1:1.5b"]
42
+ MODEL = st.sidebar.selectbox("Choose a Model", model_options, index=0)
43
+
44
+ # add advanced settings
45
+ with st.sidebar.expander("Advanced Settings"):
46
+ temperature = st.slider("Temperature", 0.0, 1.0, 0.7)
47
+ top_p = st.slider("Top-P", 0.0, 1.0, 0.9)
48
+ top_k = st.slider("Top-K", 1, 100, 40)
49
+ max_tokens = st.slider("Max Tokens", 64, 2048, 512)
50
+
51
+ # max history and context size
52
+ # ----MAX_HISTORY = st.sidebar.number_input("Max History", min_value=1, max_value=10, value=2, step=1)
53
+ # ----CONTEXT_SIZE = st.sidebar.number_input("Context Size", min_value=1024, max_value=16384, value=8192, step=1024)
54
+ MAX_HISTORY = 2
55
+ CONTEXT_SIZE = 8192
56
+
57
+ # ---- Function to Clear Memory When Settings Change ---- #
58
+ def clear_memory():
59
+ st.session_state.chat_history = []
60
+ st.session_state.memory = ConversationBufferMemory(return_messages=True) # Reset memory
61
+
62
+ # Clear memory if settings are changed
63
+ if "prev_context_size" not in st.session_state or st.session_state.prev_context_size != CONTEXT_SIZE:
64
+ clear_memory()
65
+ st.session_state.prev_context_size = CONTEXT_SIZE
66
+
67
+ # ---- Initialize Chat Memory ---- #
68
+ if "chat_history" not in st.session_state:
69
+ st.session_state.chat_history = []
70
+
71
+ if "memory" not in st.session_state:
72
+ st.session_state.memory = ConversationBufferMemory(return_messages=True)
73
+
74
+ # ---- LangChain LLM Setup ---- #
75
+ llm = ChatOllama(
76
+ model=MODEL,
77
+ streaming=True,
78
+ temperature=temperature,
79
+ top_p=top_p,
80
+ top_k=top_k,
81
+ num_predict=max_tokens,
82
+ num_ctx=CONTEXT_SIZE,
83
+ )
84
+
85
+ # for summarize button
86
+ if st.sidebar.button("Summarize Chat"):
87
+ with st.spinner("Summarizing..."):
88
+ # Format history nicely
89
+ history_text = "\n".join(
90
+ [f"{m['role']}: {m['content']}" for m in st.session_state.chat_history]
91
+ )
92
+
93
+ # Build prompt
94
+ summary_prompt = [
95
+ {"role": "system", "content": "You are a helpful assistant that summarizes conversations."},
96
+ {"role": "user", "content": f"Please summarize this conversation:\n\n{history_text}"}
97
+ ]
98
+
99
+ # Call model using LangChain
100
+ summary_result = llm.invoke(summary_prompt[1]["content"])
101
+ summary = summary_result.content if hasattr(summary_result, 'content') else str(summary_result)
102
+
103
+ # Save summary
104
+ st.session_state.chat_history.append(
105
+ {"role": "assistant", "content": summary}
106
+ )
107
+
108
+ # Show in chat
109
+ with st.chat_message("assistant"):
110
+ st.markdown(summary)
111
+
112
+ # ---- Prompt Template ---- #
113
+ prompt_template = PromptTemplate(
114
+ input_variables=["history", "human_input"],
115
+ template="{history}\nUser: {human_input}\nAssistant:"
116
+ )
117
+
118
+ chain = LLMChain(llm=llm, prompt=prompt_template, memory=st.session_state.memory)
119
+
120
+ # ---- Display Chat History ---- #
121
+ for msg in st.session_state.chat_history:
122
+ with st.chat_message(msg["role"]):
123
+ st.markdown(msg["content"])
124
+
125
+ # ---- Trim Function (Removes Oldest Messages) ---- #
126
+ def trim_memory():
127
+ while len(st.session_state.chat_history) > MAX_HISTORY * 2: # Each cycle has 2 messages (User + AI)
128
+ st.session_state.chat_history.pop(0) # Remove oldest User message
129
+ if st.session_state.chat_history:
130
+ st.session_state.chat_history.pop(0) # Remove oldest AI response
131
+
132
+ # ---- Handle User Input ---- #
133
+ if prompt := st.chat_input("Say something"):
134
+ # Show User Input Immediately
135
+ with st.chat_message("user"):
136
+ st.markdown(prompt)
137
+
138
+ st.session_state.chat_history.append({"role": "user", "content": prompt}) # Store user input
139
+
140
+ # Trim chat history before generating response
141
+ trim_memory()
142
+
143
+ # ---- Get AI Response (Streaming) ---- #
144
+ with st.chat_message("assistant"):
145
+ response_container = st.empty()
146
+ full_response = ""
147
+
148
+ for chunk in chain.stream({"human_input": prompt}):
149
+ if isinstance(chunk, dict) and "text" in chunk:
150
+ text_chunk = chunk["text"]
151
+ full_response += text_chunk
152
+ response_container.markdown(full_response)
153
+
154
+ # Store response in session_state
155
+ st.session_state.chat_history.append({"role": "assistant", "content": full_response})
156
+
157
+ # Trim history after storing the response
158
+ trim_memory()
159
+