macayaven commited on
Commit
0171b0c
·
verified ·
1 Parent(s): 9e2991b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -11
app.py CHANGED
@@ -149,11 +149,31 @@ class CBTChatbot:
149
  self.identified_distortions: list[tuple[str, float]] = []
150
  self.memory_size = max(2, int(memory_size))
151
 
152
- def _history_to_context(self, history: list[list[str]]) -> list[dict]:
153
- """Convert Chatbot history [[user, assistant], ...] to agent context[{user,assistant}]"""
 
 
 
 
 
154
  ctx: list[dict] = []
155
- for turn in history or []:
156
- if isinstance(turn, list | tuple) and len(turn) == 2:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  ctx.append({"user": turn[0] or "", "assistant": turn[1] or ""})
158
  return ctx[-self.memory_size :]
159
 
@@ -683,12 +703,26 @@ def create_app(language='en'):
683
  )
684
  return
685
 
686
- # Start streaming the assistant reply
687
  history = history or []
688
- history.append([message, ""]) # placeholder for assistant
689
- # Enforce memory cap while streaming
690
- if len(history) > chatbot.memory_size:
691
- history = history[-chatbot.memory_size :]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
692
 
693
  # Choose response source: true token streaming via HF Inference
694
  try:
@@ -724,7 +758,13 @@ def create_app(language='en'):
724
  if not chunk:
725
  continue
726
  acc += str(chunk)
727
- history[-1][1] = acc
 
 
 
 
 
 
728
  # yield streaming frame
729
  yield (
730
  history,
@@ -1013,4 +1053,4 @@ def create_app(language='en'):
1013
  # Launch the app
1014
  if __name__ == "__main__":
1015
  app = create_app(language='en')
1016
- app.launch(share=False, show_error=True, show_api=False)
 
149
  self.identified_distortions: list[tuple[str, float]] = []
150
  self.memory_size = max(2, int(memory_size))
151
 
152
+ def _history_to_context(self, history) -> list[dict]:
153
+ """Convert Chatbot history to agent context.
154
+
155
+ Supports both legacy [[user, assistant], ...] and new Gradio
156
+ messages format [{role, content}, ...]. Returns a list of
157
+ {user, assistant} dicts capped to memory_size.
158
+ """
159
  ctx: list[dict] = []
160
+ if not history:
161
+ return ctx
162
+ # New messages format
163
+ if isinstance(history, list) and history and isinstance(history[0], dict):
164
+ pending_user = None
165
+ for msg in history:
166
+ role = str(msg.get("role", ""))
167
+ content = str(msg.get("content", ""))
168
+ if role == "user":
169
+ pending_user = content
170
+ elif role == "assistant" and pending_user is not None:
171
+ ctx.append({"user": pending_user, "assistant": content})
172
+ pending_user = None
173
+ return ctx[-self.memory_size :]
174
+ # Legacy tuple format
175
+ for turn in history:
176
+ if isinstance(turn, (list, tuple)) and len(turn) == 2:
177
  ctx.append({"user": turn[0] or "", "assistant": turn[1] or ""})
178
  return ctx[-self.memory_size :]
179
 
 
703
  )
704
  return
705
 
706
+ # Start streaming the assistant reply (messages format)
707
  history = history or []
708
+ # Append user message then assistant placeholder
709
+ try:
710
+ history.append({"role": "user", "content": message})
711
+ except Exception:
712
+ history = list(history) + [{"role": "user", "content": message}]
713
+ history.append({"role": "assistant", "content": ""})
714
+ # Optional prune to last N pairs to keep UI light
715
+ try:
716
+ pairs = chatbot._history_to_context(history[:-1])
717
+ pruned: list[dict] = []
718
+ for p in pairs:
719
+ pruned.append({"role": "user", "content": p.get("user", "")})
720
+ pruned.append({"role": "assistant", "content": p.get("assistant", "")})
721
+ pruned.append({"role": "user", "content": message})
722
+ pruned.append({"role": "assistant", "content": ""})
723
+ history = pruned
724
+ except Exception:
725
+ pass
726
 
727
  # Choose response source: true token streaming via HF Inference
728
  try:
 
758
  if not chunk:
759
  continue
760
  acc += str(chunk)
761
+ if isinstance(history[-1], dict):
762
+ history[-1]["content"] = acc
763
+ else:
764
+ try:
765
+ history[-1][1] = acc
766
+ except Exception:
767
+ pass
768
  # yield streaming frame
769
  yield (
770
  history,
 
1053
  # Launch the app
1054
  if __name__ == "__main__":
1055
  app = create_app(language='en')
1056
+ app.launch(share=True, show_error=True, show_api=False)