anurag051194 commited on
Commit
c11fdf5
·
verified ·
1 Parent(s): 05f3ee9

Add thinking trace visibility control

Browse files

Let users hide reasoning traces independently of reasoning generation and make the collapsible trace affordance clearer.

Files changed (1) hide show
  1. app.py +74 -88
app.py CHANGED
@@ -24,8 +24,6 @@ import gradio as gr
24
 
25
  MODEL_ID = "webAI-Official/TwIL-LM3-Pro"
26
  MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "8192"))
27
- # The reasoning trace alone often runs ~2k tokens, so leave room for the answer.
28
- DEFAULT_MAX_NEW_TOKENS = 4096
29
  ASSETS = Path(__file__).resolve().parent / "brand"
30
  AVATAR = ASSETS / "avatar.svg"
31
 
@@ -190,29 +188,14 @@ html, body, #root, .gradio-container, .gradio-container > .main,
190
  .gradio-container .wrap.default {
191
  background: transparent !important;
192
  }
193
- /* Gradio's root is a flex column locked to the viewport. Make it a normal
194
- document so content taller than the window extends the page and scrolls. */
195
- html, body {
196
- display: block !important;
197
- height: auto !important;
198
- min-height: 100% !important;
199
- max-height: none !important;
200
- max-width: none !important;
201
- margin: 0 !important;
202
- overflow-x: hidden !important;
203
- overflow-y: auto !important;
204
- }
205
- .gradio-container, .gradio-container > .main, .fillable,
206
  .contain, .app {
207
- display: flex !important;
208
- flex-direction: column !important;
209
- flex-grow: 0 !important;
210
- height: auto !important;
211
  min-height: 100vh !important;
212
- max-height: none !important;
213
  max-width: none !important;
214
  margin: 0 !important;
215
- overflow: visible !important;
216
  }
217
  .gradio-container, .main.fillable, .contain {
218
  display: flex !important;
@@ -229,15 +212,15 @@ footer, .footer, .built-with, .settings, .settings-bar, .show-api,
229
  }
230
 
231
  #app-shell {
232
- flex: 0 0 auto !important;
233
- height: auto !important;
234
- max-height: none !important;
235
- min-height: 100vh !important;
236
  display: flex !important;
237
  flex-direction: column !important;
238
- padding: 16px 24px 24px !important;
239
  box-sizing: border-box !important;
240
- overflow: visible !important;
241
  background: var(--weba-canvas) !important;
242
  }
243
  #app-shell > .gap, #app-shell > div {
@@ -249,8 +232,8 @@ footer, .footer, .built-with, .settings, .settings-bar, .show-api,
249
  #app-shell > #twil-chat,
250
  #app-shell > .block:has(#twil-chat),
251
  #app-shell > div:has(#twil-chat) {
252
- flex: 0 0 auto !important;
253
- min-height: auto !important;
254
  height: auto !important;
255
  }
256
 
@@ -339,30 +322,30 @@ footer, .footer, .built-with, .settings, .settings-bar, .show-api,
339
  #twil-chat {
340
  max-width: 768px !important;
341
  width: 100% !important;
342
- height: auto !important;
343
- max-height: none !important;
344
  margin: 0 auto !important;
345
- flex: 0 0 auto !important;
346
  display: flex !important;
347
  flex-direction: column !important;
348
- overflow: visible !important;
349
  }
350
  #twil-chat > .wrapper {
351
- flex: 0 0 auto !important;
352
- height: auto !important;
353
- max-height: none !important;
354
  min-height: 0 !important;
355
  display: flex !important;
356
  flex-direction: column !important;
357
- overflow: visible !important;
358
  }
359
  #twil-chat .bubble-wrap {
360
- flex: 0 0 auto !important;
361
- height: auto !important;
362
- min-height: 280px !important;
363
- max-height: none !important;
364
  overflow-x: hidden !important;
365
- overflow-y: visible !important;
 
 
 
366
  padding-right: 8px !important;
367
  }
368
  #twil-chat .bubble-wrap::-webkit-scrollbar {
@@ -398,6 +381,14 @@ footer, .footer, .built-with, .settings, .settings-bar, .show-api,
398
  box-shadow: none !important;
399
  color: var(--weba-muted) !important;
400
  }
 
 
 
 
 
 
 
 
401
 
402
  #composer-row {
403
  max-width: 768px !important;
@@ -561,15 +552,12 @@ footer, .footer, .built-with, .settings, .settings-bar, .show-api,
561
  flex-shrink: 0;
562
  }
563
 
564
- /* Tabs grow with their content so the document can scroll. */
565
  #twil-tabs {
566
- flex: 0 0 auto !important;
567
- min-height: auto !important;
568
- height: auto !important;
569
- max-height: none !important;
570
  display: flex !important;
571
  flex-direction: column !important;
572
- overflow: visible !important;
573
  background: transparent !important;
574
  border: none !important;
575
  box-shadow: none !important;
@@ -600,11 +588,9 @@ footer, .footer, .built-with, .settings, .settings-bar, .show-api,
600
  border-bottom-color: var(--weba-fg) !important;
601
  }
602
  #twil-tabs .tabitem {
603
- flex: 0 0 auto !important;
604
- min-height: auto !important;
605
- height: auto !important;
606
- max-height: none !important;
607
- overflow: visible !important;
608
  background: transparent !important;
609
  border: none !important;
610
  box-shadow: none !important;
@@ -612,10 +598,8 @@ footer, .footer, .built-with, .settings, .settings-bar, .show-api,
612
  }
613
  #tab-chat > .gap, #tab-chat > .column,
614
  #tab-chat, #tab-chat .column:has(> div > #twil-chat) {
615
- height: auto !important;
616
- max-height: none !important;
617
  min-height: 0 !important;
618
- overflow: visible !important;
619
  }
620
  #tab-chat > .gap, #tab-chat > .column {
621
  display: flex !important;
@@ -623,15 +607,12 @@ footer, .footer, .built-with, .settings, .settings-bar, .show-api,
623
  }
624
  #tab-chat .block:has(#twil-chat),
625
  #tab-chat div:has(> #twil-chat) {
626
- flex: 0 0 auto !important;
627
- min-height: auto !important;
628
  height: auto !important;
629
- overflow: visible !important;
630
  }
631
  #tab-showcase {
632
- overflow: visible !important;
633
- height: auto !important;
634
- max-height: none !important;
635
  }
636
 
637
  /* Showcase cards */
@@ -776,11 +757,6 @@ def _strip_thinking(text: str) -> str:
776
  def _parse_think(raw: str) -> tuple[str, str, bool]:
777
  """Return (think, answer, think_open) from a possibly streaming reply."""
778
  open_idx = raw.find(THINK_OPEN)
779
- if open_idx == -1 and THINK_CLOSE in raw:
780
- # The chat template can emit the opening tag in the prompt, so the
781
- # completion only carries the closing one.
782
- raw = THINK_OPEN + raw
783
- open_idx = 0
784
  if open_idx == -1:
785
  # A partially streamed opening tag is not an answer yet.
786
  if raw.strip() and THINK_OPEN.startswith(raw.strip()):
@@ -804,8 +780,8 @@ def _parse_think(raw: str) -> tuple[str, str, bool]:
804
  def _gpu_seconds(history, max_new_tokens=2048, *args, **kwargs):
805
  # Scale the ZeroGPU reservation with the requested output budget. The
806
  # platform caps a single reservation at five minutes.
807
- tokens = int(max_new_tokens or DEFAULT_MAX_NEW_TOKENS)
808
- return min(300, max(30, 30 + tokens // 30))
809
 
810
 
811
  def _history_for_model(history: list) -> list[dict]:
@@ -892,23 +868,12 @@ def _stream_tokens(conversation: list[dict], max_new_tokens: int, temperature: f
892
  generate_kwargs["temperature"] = float(temperature)
893
  generate_kwargs["top_p"] = float(top_p)
894
 
895
- prompt_tail = tokenizer.decode(input_ids[0, -8:], skip_special_tokens=False)
896
- acc = THINK_OPEN if prompt_tail.rstrip().endswith(THINK_OPEN) else ""
897
-
898
  Thread(target=model.generate, kwargs=generate_kwargs, daemon=True).start()
 
899
  for text in streamer:
900
  acc += text
901
  yield acc
902
 
903
- generated = len(tokenizer.encode(acc, add_special_tokens=False))
904
- if generated >= int(max_new_tokens) - 4:
905
- if THINK_OPEN in acc and THINK_CLOSE not in acc:
906
- acc += THINK_CLOSE
907
- yield acc + (
908
- f"\n\n*Stopped at the {int(max_new_tokens):,}-token limit. "
909
- "Raise **Max new tokens** under Parameters for a complete answer.*"
910
- )
911
-
912
 
913
  def queue_message(message, history):
914
  """Paint the user turn immediately so the GPU wait is not a blank screen."""
@@ -928,7 +893,14 @@ def queue_message(message, history):
928
 
929
 
930
  @spaces.GPU(duration=_gpu_seconds)
931
- def generate_reply(history, max_new_tokens, temperature, top_p, enable_thinking):
 
 
 
 
 
 
 
932
  history = [dict(m) if isinstance(m, dict) else m for m in (history or [])]
933
  if not any(m.get("role") == "user" for m in history):
934
  yield history
@@ -964,13 +936,15 @@ def generate_reply(history, max_new_tokens, temperature, top_p, enable_thinking)
964
  conversation, max_new_tokens, temperature, top_p, enable_thinking
965
  ):
966
  think, answer, think_open = _parse_think(raw)
967
- if think or think_open:
968
  think_msg["content"] = think
969
  think_msg["metadata"] = {
970
  "title": "Logicizing…" if think_open else "Logic",
971
  "status": "pending" if think_open else "done",
972
  }
973
  if answer:
 
 
974
  answer_msg["content"] = answer
975
  if not any(m is answer_msg for m in history):
976
  history.append(answer_msg)
@@ -984,15 +958,15 @@ def generate_reply(history, max_new_tokens, temperature, top_p, enable_thinking)
984
  answer_msg["content"] = ""
985
  yield history
986
 
987
- if think_msg["content"]:
988
  think_msg["metadata"] = {"title": "Logic", "status": "done"}
989
  yield history
990
- elif think_msg in history and not think_msg["content"]:
991
  history.remove(think_msg)
992
  yield history
993
 
994
 
995
- with gr.Blocks(fill_height=False, fill_width=True, elem_id="app-root") as demo:
996
  with gr.Column(elem_id="app-shell"):
997
  gr.HTML(HEADER)
998
  with gr.Tabs(elem_id="twil-tabs") as tabs:
@@ -1011,6 +985,7 @@ with gr.Blocks(fill_height=False, fill_width=True, elem_id="app-root") as demo:
1011
  line_breaks=False,
1012
  elem_id="twil-chat",
1013
  scale=1,
 
1014
  autoscroll=True,
1015
  )
1016
  with gr.Row(elem_id="chips-row") as chips_row:
@@ -1030,10 +1005,14 @@ with gr.Blocks(fill_height=False, fill_width=True, elem_id="app-root") as demo:
1030
  )
1031
  send = gr.Button("↑", elem_id="send-btn", scale=0)
1032
  with gr.Accordion("Parameters", open=False, elem_id="params-box"):
1033
- max_new_tokens = gr.Slider(256, 16384, value=DEFAULT_MAX_NEW_TOKENS, step=256, label="Max new tokens")
1034
  temperature = gr.Slider(0, 1.5, value=0, step=0.05, label="Temperature (0 = greedy)")
1035
  top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p")
1036
  enable_thinking = gr.Checkbox(value=True, label="Enable thinking")
 
 
 
 
1037
  gr.HTML('<p class="twil-disclaimer">This is AI and it can make mistakes</p>')
1038
  with gr.Tab("Showcase", id="showcase", elem_id="tab-showcase"):
1039
  gr.HTML(SHOWCASE_INTRO)
@@ -1068,7 +1047,14 @@ with gr.Blocks(fill_height=False, fill_width=True, elem_id="app-root") as demo:
1068
  show_progress="hidden",
1069
  ).then(
1070
  generate_reply,
1071
- [chatbot, max_new_tokens, temperature, top_p, enable_thinking],
 
 
 
 
 
 
 
1072
  chatbot,
1073
  concurrency_limit=1,
1074
  show_progress="hidden",
 
24
 
25
  MODEL_ID = "webAI-Official/TwIL-LM3-Pro"
26
  MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "8192"))
 
 
27
  ASSETS = Path(__file__).resolve().parent / "brand"
28
  AVATAR = ASSETS / "avatar.svg"
29
 
 
188
  .gradio-container .wrap.default {
189
  background: transparent !important;
190
  }
191
+ html, body, .gradio-container, .gradio-container > .main, .fillable,
 
 
 
 
 
 
 
 
 
 
 
 
192
  .contain, .app {
193
+ height: 100% !important;
 
 
 
194
  min-height: 100vh !important;
195
+ max-height: 100vh !important;
196
  max-width: none !important;
197
  margin: 0 !important;
198
+ overflow: hidden !important;
199
  }
200
  .gradio-container, .main.fillable, .contain {
201
  display: flex !important;
 
212
  }
213
 
214
  #app-shell {
215
+ flex: 1 1 auto !important;
216
+ height: 100% !important;
217
+ max-height: 100% !important;
218
+ min-height: 0 !important;
219
  display: flex !important;
220
  flex-direction: column !important;
221
+ padding: 16px 24px 12px !important;
222
  box-sizing: border-box !important;
223
+ overflow: hidden !important;
224
  background: var(--weba-canvas) !important;
225
  }
226
  #app-shell > .gap, #app-shell > div {
 
232
  #app-shell > #twil-chat,
233
  #app-shell > .block:has(#twil-chat),
234
  #app-shell > div:has(#twil-chat) {
235
+ flex: 1 1 auto !important;
236
+ min-height: 0 !important;
237
  height: auto !important;
238
  }
239
 
 
322
  #twil-chat {
323
  max-width: 768px !important;
324
  width: 100% !important;
325
+ height: 100% !important;
 
326
  margin: 0 auto !important;
327
+ flex: 1 1 auto !important;
328
  display: flex !important;
329
  flex-direction: column !important;
330
+ overflow: hidden !important;
331
  }
332
  #twil-chat > .wrapper {
333
+ flex: 1 1 auto !important;
334
+ height: 100% !important;
 
335
  min-height: 0 !important;
336
  display: flex !important;
337
  flex-direction: column !important;
338
+ overflow: hidden !important;
339
  }
340
  #twil-chat .bubble-wrap {
341
+ flex: 1 1 auto !important;
342
+ height: 100% !important;
343
+ min-height: 0 !important;
 
344
  overflow-x: hidden !important;
345
+ overflow-y: auto !important;
346
+ overscroll-behavior: contain;
347
+ scrollbar-gutter: stable;
348
+ scroll-behavior: smooth;
349
  padding-right: 8px !important;
350
  }
351
  #twil-chat .bubble-wrap::-webkit-scrollbar {
 
381
  box-shadow: none !important;
382
  color: var(--weba-muted) !important;
383
  }
384
+ #twil-chat details > summary {
385
+ cursor: pointer !important;
386
+ user-select: none;
387
+ color: var(--weba-muted) !important;
388
+ }
389
+ #twil-chat details > summary:hover {
390
+ color: var(--weba-fg) !important;
391
+ }
392
 
393
  #composer-row {
394
  max-width: 768px !important;
 
552
  flex-shrink: 0;
553
  }
554
 
555
+ /* Tabs shell: keep the chat layout filling the viewport */
556
  #twil-tabs {
557
+ flex: 1 1 auto !important;
558
+ min-height: 0 !important;
 
 
559
  display: flex !important;
560
  flex-direction: column !important;
 
561
  background: transparent !important;
562
  border: none !important;
563
  box-shadow: none !important;
 
588
  border-bottom-color: var(--weba-fg) !important;
589
  }
590
  #twil-tabs .tabitem {
591
+ flex: 1 1 auto !important;
592
+ min-height: 0 !important;
593
+ overflow: hidden !important;
 
 
594
  background: transparent !important;
595
  border: none !important;
596
  box-shadow: none !important;
 
598
  }
599
  #tab-chat > .gap, #tab-chat > .column,
600
  #tab-chat, #tab-chat .column:has(> div > #twil-chat) {
601
+ height: 100% !important;
 
602
  min-height: 0 !important;
 
603
  }
604
  #tab-chat > .gap, #tab-chat > .column {
605
  display: flex !important;
 
607
  }
608
  #tab-chat .block:has(#twil-chat),
609
  #tab-chat div:has(> #twil-chat) {
610
+ flex: 1 1 auto !important;
611
+ min-height: 0 !important;
612
  height: auto !important;
 
613
  }
614
  #tab-showcase {
615
+ overflow-y: auto !important;
 
 
616
  }
617
 
618
  /* Showcase cards */
 
757
  def _parse_think(raw: str) -> tuple[str, str, bool]:
758
  """Return (think, answer, think_open) from a possibly streaming reply."""
759
  open_idx = raw.find(THINK_OPEN)
 
 
 
 
 
760
  if open_idx == -1:
761
  # A partially streamed opening tag is not an answer yet.
762
  if raw.strip() and THINK_OPEN.startswith(raw.strip()):
 
780
  def _gpu_seconds(history, max_new_tokens=2048, *args, **kwargs):
781
  # Scale the ZeroGPU reservation with the requested output budget. The
782
  # platform caps a single reservation at five minutes.
783
+ tokens = int(max_new_tokens or 2048)
784
+ return min(300, max(30, 20 + tokens // 50))
785
 
786
 
787
  def _history_for_model(history: list) -> list[dict]:
 
868
  generate_kwargs["temperature"] = float(temperature)
869
  generate_kwargs["top_p"] = float(top_p)
870
 
 
 
 
871
  Thread(target=model.generate, kwargs=generate_kwargs, daemon=True).start()
872
+ acc = ""
873
  for text in streamer:
874
  acc += text
875
  yield acc
876
 
 
 
 
 
 
 
 
 
 
877
 
878
  def queue_message(message, history):
879
  """Paint the user turn immediately so the GPU wait is not a blank screen."""
 
893
 
894
 
895
  @spaces.GPU(duration=_gpu_seconds)
896
+ def generate_reply(
897
+ history,
898
+ max_new_tokens,
899
+ temperature,
900
+ top_p,
901
+ enable_thinking,
902
+ show_thinking_trace,
903
+ ):
904
  history = [dict(m) if isinstance(m, dict) else m for m in (history or [])]
905
  if not any(m.get("role") == "user" for m in history):
906
  yield history
 
936
  conversation, max_new_tokens, temperature, top_p, enable_thinking
937
  ):
938
  think, answer, think_open = _parse_think(raw)
939
+ if show_thinking_trace and (think or think_open):
940
  think_msg["content"] = think
941
  think_msg["metadata"] = {
942
  "title": "Logicizing…" if think_open else "Logic",
943
  "status": "pending" if think_open else "done",
944
  }
945
  if answer:
946
+ if not show_thinking_trace and think_msg in history:
947
+ history.remove(think_msg)
948
  answer_msg["content"] = answer
949
  if not any(m is answer_msg for m in history):
950
  history.append(answer_msg)
 
958
  answer_msg["content"] = ""
959
  yield history
960
 
961
+ if show_thinking_trace and think_msg["content"]:
962
  think_msg["metadata"] = {"title": "Logic", "status": "done"}
963
  yield history
964
+ elif think_msg in history:
965
  history.remove(think_msg)
966
  yield history
967
 
968
 
969
+ with gr.Blocks(fill_height=True, fill_width=True, elem_id="app-root") as demo:
970
  with gr.Column(elem_id="app-shell"):
971
  gr.HTML(HEADER)
972
  with gr.Tabs(elem_id="twil-tabs") as tabs:
 
985
  line_breaks=False,
986
  elem_id="twil-chat",
987
  scale=1,
988
+ height="100%",
989
  autoscroll=True,
990
  )
991
  with gr.Row(elem_id="chips-row") as chips_row:
 
1005
  )
1006
  send = gr.Button("↑", elem_id="send-btn", scale=0)
1007
  with gr.Accordion("Parameters", open=False, elem_id="params-box"):
1008
+ max_new_tokens = gr.Slider(256, 16384, value=2048, step=256, label="Max new tokens")
1009
  temperature = gr.Slider(0, 1.5, value=0, step=0.05, label="Temperature (0 = greedy)")
1010
  top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p")
1011
  enable_thinking = gr.Checkbox(value=True, label="Enable thinking")
1012
+ show_thinking_trace = gr.Checkbox(
1013
+ value=True,
1014
+ label="Show thinking trace (use its arrow to expand or collapse)",
1015
+ )
1016
  gr.HTML('<p class="twil-disclaimer">This is AI and it can make mistakes</p>')
1017
  with gr.Tab("Showcase", id="showcase", elem_id="tab-showcase"):
1018
  gr.HTML(SHOWCASE_INTRO)
 
1047
  show_progress="hidden",
1048
  ).then(
1049
  generate_reply,
1050
+ [
1051
+ chatbot,
1052
+ max_new_tokens,
1053
+ temperature,
1054
+ top_p,
1055
+ enable_thinking,
1056
+ show_thinking_trace,
1057
+ ],
1058
  chatbot,
1059
  concurrency_limit=1,
1060
  show_progress="hidden",