Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
unsloth chat: parse the streamed Markdown when a frame is drawn, not on every chunk (#16994)
Daniel Han8360b2c29282
diff --git a/unsloth_cli/_inference.py b/unsloth_cli/_inference.pyindex 403f5f760b0..471ad9eb9e8 100644--- a/unsloth_cli/_inference.py+++ b/unsloth_cli/_inference.py@@ -338,21 +338,35 @@ def stream_to_stdout(stream, show_thinking: bool) -> str:return raw+class _LatestMarkdown:+ # visible_text() and Markdown() each scan the whole reply: run them per drawn frame, not per chunk.+ def __init__(self, show_thinking: bool):+ self.state = ("", False) # (raw, final), swapped whole so the Live thread never sees a mix+ self._show_thinking = show_thinking+ self._built = None++ def __rich_console__(self, console, options):+ from rich.markdown import Markdown+ from rich.text import Text++ state = self.state+ if self._built is None or self._built[0] is not state:+ text = visible_text(state[0], self._show_thinking, final = state[1])+ self._built = (state, Markdown(text) if text.strip() else Text(""))+ yield self._built[1]++def stream_markdown(stream, show_thinking: bool, *, console) -> str:from rich.live import Live- from rich.markdown import Markdown- from rich.text import Textraw = ""- with Live(console = console, refresh_per_second = 12, vertical_overflow = "visible") as live:+ view = _LatestMarkdown(show_thinking)+ with Live(view, console = console, refresh_per_second = 12, vertical_overflow = "visible"):for chunk in stream:- if not isinstance(chunk, str):- continue- raw = chunk- visible = visible_text(chunk, show_thinking)- live.update(Markdown(visible) if visible.strip() else Text(""))- visible = visible_text(raw, show_thinking, final = True)- live.update(Markdown(visible) if visible.strip() else Text(""))+ if isinstance(chunk, str):+ raw = chunk+ view.state = (raw, False)+ view.state = (raw, True)return rawdiff --git a/unsloth_cli/tests/test_stream_markdown_render.py b/unsloth_cli/tests/test_stream_markdown_render.pynew file mode 100644index 00000000000..aea508ce96e--- /dev/null+++ b/unsloth_cli/tests/test_stream_markdown_render.py@@ -0,0 +1,70 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""`unsloth chat` parses its Markdown when a frame is drawn, not once per streamed chunk."""++from __future__ import annotations++import io++import rich.markdown+from rich.console import Console++import unsloth_cli._inference as inference+from unsloth_cli._inference import stream_markdown++PARA = "Some **bold** text with `code` and a list:\n\n- one\n- two\n\n"+++def _chunks(text, step = 3):+ return [text[:n] for n in range(step, len(text) + step, step)]+++def _render(chunks, show_thinking, *, terminal):+ buf = io.StringIO()+ console = Console(file = buf, width = 80, force_terminal = terminal, color_system = None)+ raw = stream_markdown(iter([*chunks, {"meta": 1}]), show_thinking, console = console)+ return raw, buf.getvalue()+++def test_parses_per_frame_not_per_chunk(monkeypatch):+ built, filtered = [], []+ real_init = rich.markdown.Markdown.__init__+ real_visible = inference.visible_text++ def _counting(self, *args, **kwargs):+ built.append(1)+ real_init(self, *args, **kwargs)++ def _counting_visible(*args, **kwargs):+ filtered.append(1)+ return real_visible(*args, **kwargs)++ monkeypatch.setattr(rich.markdown.Markdown, "__init__", _counting)+ monkeypatch.setattr(inference, "visible_text", _counting_visible)+ text = PARA * 60+ chunks = _chunks(text)+ raw, _ = _render(chunks, False, terminal = False)+ assert raw == text+ assert len(chunks) > 1000+ assert len(built) < 50+ assert len(filtered) < 50+++def test_final_output_matches_the_full_reply():+ for text, show in [+ (PARA * 5, False),+ ("<think>hidden reasoning</think>" + PARA, False),+ ("<think>shown reasoning</think>" + PARA, True),+ ("partial <thi", False),+ (" ", False),+ ]:+ raw, out = _render(_chunks(text), show, terminal = False)+ assert raw == text+ assert out == _render([text], show, terminal = False)[1]+++def test_terminal_stream_renders():+ raw, out = _render(_chunks(PARA * 20), False, terminal = True)+ assert raw == PARA * 20+ assert "bold" in out