Anirudh Esthuri commited on
Commit
23c7579
Β·
1 Parent(s): acaa797

Simplify UI layout

Browse files
Files changed (1) hide show
  1. app.py +63 -207
app.py CHANGED
@@ -1,151 +1,80 @@
1
- import os
2
- import sys
3
- import traceback
4
  from typing import cast
5
 
6
- # Print to container logs for debugging
7
- print("=" * 50, file=sys.stderr)
8
- print("Starting app.py...", file=sys.stderr)
9
- print("=" * 50, file=sys.stderr)
10
-
11
  import streamlit as st
12
 
13
- print("Streamlit imported successfully", file=sys.stderr)
14
-
15
- # Configure Streamlit for Hugging Face Spaces
16
- # Port is set via command line argument in Dockerfile
17
- # Don't set STREAMLIT_SERVER_PORT here to avoid conflicts
18
- os.environ["STREAMLIT_SERVER_ADDRESS"] = "0.0.0.0"
19
- print("Set STREAMLIT_SERVER_ADDRESS", file=sys.stderr)
20
-
21
- # Try to import modules with error handling
22
- print("Attempting to import modules...", file=sys.stderr)
23
- try:
24
- from gateway_client import delete_profile, ingest_and_rewrite
25
- print("βœ“ gateway_client imported", file=sys.stderr)
26
- from llm import chat, set_model
27
- print("βœ“ llm imported", file=sys.stderr)
28
- from model_config import MODEL_CHOICES, MODEL_TO_PROVIDER
29
- print("βœ“ model_config imported", file=sys.stderr)
30
- IMPORTS_SUCCESSFUL = True
31
- print("All imports successful!", file=sys.stderr)
32
- except Exception as e:
33
- IMPORTS_SUCCESSFUL = False
34
- IMPORT_ERROR = str(e)
35
- IMPORT_TRACEBACK = traceback.format_exc()
36
- print(f"βœ— Import failed: {IMPORT_ERROR}", file=sys.stderr)
37
- print(IMPORT_TRACEBACK, file=sys.stderr)
38
- # Create dummy functions to prevent NameError
39
- def delete_profile(user_id: str) -> bool:
40
- return False
41
- def ingest_and_rewrite(user_id: str, query: str, model_type: str = "openai") -> str:
42
- return query
43
- def chat(messages, persona):
44
- return "Error: Could not initialize chat function", 0, 0, 0
45
- def set_model(model_id: str) -> None:
46
- pass
47
- MODEL_CHOICES = ["gpt-4.1-mini"]
48
- MODEL_TO_PROVIDER = {"gpt-4.1-mini": "openai"}
49
 
50
 
51
  def rewrite_message(
52
- msg: str, persona_name: str, show_rationale: bool, skip_rewrite: bool, provider: str = "openai"
 
 
 
 
53
  ) -> str:
 
54
  if skip_rewrite:
55
  rewritten_msg = msg
56
  if show_rationale:
57
  rewritten_msg += " At the beginning of your response, please say the following in ITALIC: 'Persona Rationale: No personalization applied.'. Begin your answer on the next line."
58
- else:
59
- try:
60
- rewritten_msg = ingest_and_rewrite(
61
- user_id=persona_name, query=msg, model_type=provider
62
- )
63
- if show_rationale:
64
- rewritten_msg += " At the beginning of your response, please say the following in ITALIC: 'Persona Rationale: ' followed by 1 sentence about how your reasoning for how the persona traits influenced this response, also in italics. Begin your answer on the next line."
65
 
66
- except Exception as e:
67
- # If backend is unavailable, use original message without rewriting
68
- st.warning(f"Backend memory server unavailable. Using message without personalization: {e}")
69
- rewritten_msg = msg
70
- if show_rationale:
71
- rewritten_msg += " At the beginning of your response, please say the following in ITALIC: 'Persona Rationale: No personalization applied (backend unavailable).'. Begin your answer on the next line."
72
- return rewritten_msg
 
 
 
 
 
 
 
 
73
 
74
 
75
  # ──────────────────────────────────────────────────────────────
76
  # Page setup & CSS
77
  # ──────────────────────────────────────────────────────────────
78
- print("Setting up page config...", file=sys.stderr)
79
- try:
80
- st.set_page_config(page_title="MemMachine Chatbot", layout="wide")
81
- print("βœ“ Page config set", file=sys.stderr)
82
- except Exception as e:
83
- print(f"βœ— Failed to set page config: {e}", file=sys.stderr)
84
- st.error(f"Failed to set page config: {e}")
85
-
86
- # Show import errors if any
87
- if not IMPORTS_SUCCESSFUL:
88
- print("Showing import error to user...", file=sys.stderr)
89
- st.error("⚠️ Application Error: Failed to import required modules")
90
- st.error(f"Error: {IMPORT_ERROR}")
91
- with st.expander("Show full error details"):
92
- st.code(IMPORT_TRACEBACK)
93
- st.stop()
94
-
95
- # Debug: Show that app is loading
96
- print("Rendering initial content...", file=sys.stderr)
97
- sys.stderr.flush() # Force flush to ensure logs appear
98
- st.markdown(
99
- '<div class="pill on">πŸš€ Playground Ready</div>',
100
- unsafe_allow_html=True,
101
- )
102
- print("βœ“ Initial content rendered", file=sys.stderr)
103
- sys.stderr.flush()
104
 
105
  try:
106
  with open("./styles.css") as f:
107
  st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
108
  except FileNotFoundError:
109
- st.markdown("<style></style>", unsafe_allow_html=True)
110
 
111
 
112
  # ──────────────────────────────────────────────────────────────
113
  # Sidebar
114
  # ──────────────────────────────────────────────────────────────
115
- try:
116
- with st.sidebar:
117
- try:
118
- st.image("./assets/memmachine_logo.png", use_container_width=True)
119
- except (FileNotFoundError, Exception) as e:
120
- st.markdown("### MemMachine")
121
-
122
- st.markdown("#### Choose Model")
123
-
124
- try:
125
- model_id = st.selectbox(
126
- "Choose Model", MODEL_CHOICES, index=0, label_visibility="collapsed"
127
- )
128
- provider = MODEL_TO_PROVIDER[model_id]
129
- set_model(model_id)
130
- except Exception as e:
131
- st.error(f"Error in model selection: {e}")
132
- model_id = MODEL_CHOICES[0] if MODEL_CHOICES else "gpt-4.1-mini"
133
- provider = MODEL_TO_PROVIDER.get(model_id, "openai")
134
- set_model(model_id)
135
- except Exception as e:
136
- st.error(f"Error initializing sidebar: {e}")
137
- import traceback
138
- st.code(traceback.format_exc())
139
- # Set defaults
140
- model_id = MODEL_CHOICES[0] if MODEL_CHOICES else "gpt-4.1-mini"
141
  provider = MODEL_TO_PROVIDER.get(model_id, "openai")
142
- selected_persona = "Charlie"
143
- persona_name = "Charlie"
144
- skip_rewrite = False
145
- compare_personas = False
146
- show_rationale = False
147
- else:
148
- # Continue with sidebar if no exception
149
  st.markdown("#### Choose user persona")
150
  selected_persona = st.selectbox(
151
  "Choose user persona",
@@ -174,80 +103,7 @@ else:
174
  st.error(f"Failed to delete profile for '{persona_name}'.")
175
  st.divider()
176
 
177
- # ──────────────────────────────────────────────────────────────
178
- # Hero / Context panels
179
- # ──────────────────────────────────────────────────────────────
180
- persona_badge = persona_name if persona_name == selected_persona else f"{persona_name} β€’ custom"
181
-
182
- hero_html = f"""
183
- <div class="hero-card">
184
- <div>
185
- <p class="eyebrow">Live Persona Playground</p>
186
- <h2>MemMachine Conversational Memory</h2>
187
- <p>Use rapid persona rewrites, compare against control personas, and stream
188
- LLM output from your preferred provider without leaving this panel.</p>
189
- </div>
190
- <div class="status-chip">
191
- <span>Active model</span>
192
- <strong>{model_id}</strong>
193
- <small>{provider.title()}</small>
194
- </div>
195
- </div>
196
- """
197
- st.markdown(hero_html, unsafe_allow_html=True)
198
-
199
- stat_cols = st.columns(3)
200
- stat_cols[0].markdown(
201
- f"""
202
- <div class="stat-card">
203
- <span>Persona</span>
204
- <h4>{persona_badge}</h4>
205
- </div>
206
- """,
207
- unsafe_allow_html=True,
208
- )
209
- stat_cols[1].markdown(
210
- f"""
211
- <div class="stat-card">
212
- <span>Comparison mode</span>
213
- <h4>{"Control vs Persona" if compare_personas else "Single persona"}</h4>
214
- </div>
215
- """,
216
- unsafe_allow_html=True,
217
- )
218
- stat_cols[2].markdown(
219
- f"""
220
- <div class="stat-card">
221
- <span>Rewrite</span>
222
- <h4>{"Enabled" if not skip_rewrite else "Skipped"}</h4>
223
- </div>
224
- """,
225
- unsafe_allow_html=True,
226
- )
227
-
228
- st.markdown(
229
- f"""
230
- <div class="pill-group">
231
- <span class="pill {'on' if not skip_rewrite else ''}">Rewrite</span>
232
- <span class="pill {'on' if compare_personas else ''}">Compare personas</span>
233
- <span class="pill {'on' if show_rationale else ''}">Persona rationale</span>
234
- <span class="pill on">Backend: {os.getenv("MEMORY_SERVER_URL", "default")}</span>
235
- </div>
236
- """,
237
- unsafe_allow_html=True,
238
- )
239
-
240
- with st.expander("How to use this playground", expanded=False):
241
- st.markdown(
242
- """
243
- 1. Pick a model + persona in the sidebar.
244
- 2. Toggle rewrite / comparison to control how memories are applied.
245
- 3. Type a message below β€” MemMachine will rewrite user input if enabled, call the model, and stream the response.
246
- 4. Use *Clear chat* or *Delete profile* to reset memories.
247
- """
248
- )
249
 
250
- # ──────────────────────────────────────────────────────────────
251
  # ──────────────────────────────────────────────────────────────
252
  # Session state
253
  # ──────────────────────────────────────────────────────────────
@@ -285,12 +141,8 @@ def append_user_turn(msgs: list[dict], new_user_msg: str) -> list[dict]:
285
  # ──────────────────────────────────────────────────────────────
286
  # Title
287
  # ──────────────────────────────────────────────────────────────
288
- try:
289
- st.title("MemMachine Chatbot")
290
- except Exception as e:
291
- st.error(f"Error rendering title: {e}")
292
- import traceback
293
- st.code(traceback.format_exc())
294
 
295
  # ──────────────────────────────────────────────────────────────
296
  # Chat logic
@@ -298,35 +150,39 @@ except Exception as e:
298
  msg = st.chat_input("Type your message…")
299
  if msg:
300
  st.session_state.history.append({"role": "user", "content": msg})
301
- # rewritten_msg = "Use the persona profile to personalize your naswer only when applicable.\n"
302
  if compare_personas:
303
  all_answers = {}
304
- rewritten_msg = rewrite_message(msg, persona_name, show_rationale, False, provider)
 
 
305
  msgs = clean_history(st.session_state.history, persona_name)
306
  msgs = append_user_turn(msgs, rewritten_msg)
307
- txt, lat, tok, tps = chat(msgs, persona_name)
308
  all_answers[persona_name] = txt
309
 
310
- rewritten_msg_control = rewrite_message(msg, "Control", show_rationale, True, provider)
 
 
311
  msgs_control = clean_history(st.session_state.history, "Control")
312
  msgs_control = append_user_turn(msgs_control, rewritten_msg_control)
313
- txt_control, lat, tok, tps = chat(msgs_control, "Arnold")
314
  all_answers["Control"] = txt_control
315
 
316
  st.session_state.history.append(
317
  {"role": "assistant_all", "axis": "role", "content": all_answers}
318
  )
319
  else:
320
- rewritten_msg = rewrite_message(msg, persona_name, show_rationale, skip_rewrite, provider)
 
 
321
  msgs = clean_history(st.session_state.history, persona_name)
322
  msgs = append_user_turn(msgs, rewritten_msg)
323
- txt, lat, tok, tps = chat(
324
- msgs, "Arnold" if persona_name == "Control" else persona_name
325
- )
326
  st.session_state.history.append(
327
  {"role": "assistant", "persona": persona_name, "content": txt}
328
  )
329
 
 
330
  # ──────────────────────────────────────────────────────────────
331
  # Chat history display
332
  # ───────────────────────────────────────────��──────────────────
 
 
 
 
1
  from typing import cast
2
 
 
 
 
 
 
3
  import streamlit as st
4
 
5
+ from gateway_client import delete_profile, ingest_and_rewrite
6
+ from llm import chat, set_model
7
+ from model_config import MODEL_CHOICES, MODEL_TO_PROVIDER
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
 
10
  def rewrite_message(
11
+ msg: str,
12
+ persona_name: str,
13
+ show_rationale: bool,
14
+ skip_rewrite: bool,
15
+ provider: str,
16
  ) -> str:
17
+ """Rewrite the user message via MemMachine unless skip is requested."""
18
  if skip_rewrite:
19
  rewritten_msg = msg
20
  if show_rationale:
21
  rewritten_msg += " At the beginning of your response, please say the following in ITALIC: 'Persona Rationale: No personalization applied.'. Begin your answer on the next line."
22
+ return rewritten_msg
 
 
 
 
 
 
23
 
24
+ try:
25
+ rewritten_msg = ingest_and_rewrite(
26
+ user_id=persona_name, query=msg, model_type=provider
27
+ )
28
+ if show_rationale:
29
+ rewritten_msg += " At the beginning of your response, please say the following in ITALIC: 'Persona Rationale: ' followed by 1 sentence about how your reasoning for how the persona traits influenced this response, also in italics. Begin your answer on the next line."
30
+ return rewritten_msg
31
+ except Exception as e:
32
+ st.warning(
33
+ f"Backend memory server unavailable. Using message without personalization: {e}"
34
+ )
35
+ rewritten_msg = msg
36
+ if show_rationale:
37
+ rewritten_msg += " At the beginning of your response, please say the following in ITALIC: 'Persona Rationale: No personalization applied (backend unavailable).'. Begin your answer on the next line."
38
+ return rewritten_msg
39
 
40
 
41
  # ──────────────────────────────────────────────────────────────
42
  # Page setup & CSS
43
  # ──────────────────────────────────────────────────────────────
44
+ st.set_page_config(page_title="MemMachine Chatbot", layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  try:
47
  with open("./styles.css") as f:
48
  st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)
49
  except FileNotFoundError:
50
+ pass
51
 
52
 
53
  # ──────────────────────────────────────────────────────────────
54
  # Sidebar
55
  # ──────────────────────────────────────────────────────────────
56
+ default_model = MODEL_CHOICES[0] if MODEL_CHOICES else "gpt-4.1-mini"
57
+ model_id = default_model
58
+ provider = MODEL_TO_PROVIDER.get(default_model, "openai")
59
+ selected_persona = "Charlie"
60
+ persona_name = "Charlie"
61
+ skip_rewrite = False
62
+ compare_personas = False
63
+ show_rationale = False
64
+
65
+ with st.sidebar:
66
+ try:
67
+ st.image("./assets/memmachine_logo.png", use_container_width=True)
68
+ except (FileNotFoundError, Exception):
69
+ st.markdown("### MemMachine")
70
+
71
+ st.markdown("#### Choose Model")
72
+ model_id = st.selectbox(
73
+ "Choose Model", MODEL_CHOICES, index=0, label_visibility="collapsed"
74
+ )
 
 
 
 
 
 
 
75
  provider = MODEL_TO_PROVIDER.get(model_id, "openai")
76
+ set_model(model_id)
77
+
 
 
 
 
 
78
  st.markdown("#### Choose user persona")
79
  selected_persona = st.selectbox(
80
  "Choose user persona",
 
103
  st.error(f"Failed to delete profile for '{persona_name}'.")
104
  st.divider()
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
 
107
  # ──────────────────────────────────────────────────────────────
108
  # Session state
109
  # ──────────────────────────────────────────────────────────────
 
141
  # ──────────────────────────────────────────────────────────────
142
  # Title
143
  # ──────────────────────────────────────────────────────────────
144
+ st.title("MemMachine Chatbot")
145
+
 
 
 
 
146
 
147
  # ──────────────────────────────────────────────────────────────
148
  # Chat logic
 
150
  msg = st.chat_input("Type your message…")
151
  if msg:
152
  st.session_state.history.append({"role": "user", "content": msg})
 
153
  if compare_personas:
154
  all_answers = {}
155
+ rewritten_msg = rewrite_message(
156
+ msg, persona_name, show_rationale, False, provider
157
+ )
158
  msgs = clean_history(st.session_state.history, persona_name)
159
  msgs = append_user_turn(msgs, rewritten_msg)
160
+ txt, *_ = chat(msgs, persona_name)
161
  all_answers[persona_name] = txt
162
 
163
+ rewritten_msg_control = rewrite_message(
164
+ msg, "Control", show_rationale, True, provider
165
+ )
166
  msgs_control = clean_history(st.session_state.history, "Control")
167
  msgs_control = append_user_turn(msgs_control, rewritten_msg_control)
168
+ txt_control, *_ = chat(msgs_control, "Arnold")
169
  all_answers["Control"] = txt_control
170
 
171
  st.session_state.history.append(
172
  {"role": "assistant_all", "axis": "role", "content": all_answers}
173
  )
174
  else:
175
+ rewritten_msg = rewrite_message(
176
+ msg, persona_name, show_rationale, skip_rewrite, provider
177
+ )
178
  msgs = clean_history(st.session_state.history, persona_name)
179
  msgs = append_user_turn(msgs, rewritten_msg)
180
+ txt, *_ = chat(msgs, "Arnold" if persona_name == "Control" else persona_name)
 
 
181
  st.session_state.history.append(
182
  {"role": "assistant", "persona": persona_name, "content": txt}
183
  )
184
 
185
+
186
  # ──────────────────────────────────────────────────────────────
187
  # Chat history display
188
  # ───────────────────────────────────────────��──────────────────