Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(cli): print square-bracket text in replies and dataset keys as text (#1596) (#1602)

Nariman Abdikarimc6d48e3c7d11
diff --git a/changelog.d/0.76.0/1602.fixed.md b/changelog.d/0.76.0/1602.fixed.md
new file mode 100644
index 00000000..6d793ee7
--- /dev/null
+++ b/changelog.d/0.76.0/1602.fixed.md
@@ -0,0 +1,4 @@
+- Square-bracket text in model replies and names/paths (`soup chat`, `soup diff`, `soup eval human`)
+ and dataset keys/issues (`soup data inspect`, `soup data validate`) is escaped through
+ `for_terminal` instead of parsed as Rich markup, preventing `MarkupError` crashes on
+ closing tags like `[/INST]` or `[/b]` and preserving literal text (#1596 by @Nari-Ab in #1602).
diff --git a/src/soup_cli/commands/chat.py b/src/soup_cli/commands/chat.py
index 76720599..ba68968a 100644
--- a/src/soup_cli/commands/chat.py
+++ b/src/soup_cli/commands/chat.py
@@ -182,7 +182,7 @@ def chat(
# Remove old system prompt if exists
history = [msg for msg in history if msg["role"] != "system"]
history.insert(0, {"role": "system", "content": new_system})
- console.print(f"[dim]System prompt set: {new_system}[/]\n")
+ console.print(f"[dim]System prompt set: {for_terminal(new_system)}[/]\n")
continue
# Add user message
@@ -196,7 +196,7 @@ def chat(
)
history.append({"role": "assistant", "content": response})
- console.print(f"[bold green]Assistant:[/] {response}\n")
+ console.print(f"[bold green]Assistant:[/] {for_terminal(response)}\n")
def _detect_base_model(adapter_config_path: Path) -> Optional[str]:
diff --git a/src/soup_cli/commands/data.py b/src/soup_cli/commands/data.py
index d6eb2af0..b209acb7 100644
--- a/src/soup_cli/commands/data.py
+++ b/src/soup_cli/commands/data.py
@@ -49,7 +49,7 @@ def inspect(
stats_table.add_column("Metric", style="bold")
stats_table.add_column("Value")
stats_table.add_row("Total samples", str(result["total"]))
- stats_table.add_row("Columns", ", ".join(result["columns"]))
+ stats_table.add_row("Columns", ", ".join(for_terminal(col) for col in result["columns"]))
stats_table.add_row("Avg length (chars)", str(result["avg_length"]))
stats_table.add_row("Min length", str(result["min_length"]))
stats_table.add_row("Max length", str(result["max_length"]))
@@ -120,9 +120,9 @@ def validate(
try:
fmt = detect_format(data)
- console.print(f"[dim]Auto-detected format: {fmt}[/]")
+ console.print(f"[dim]Auto-detected format: {for_terminal(fmt)}[/]")
except ValueError as exc:
- console.print(f"[red]{exc}[/]")
+ console.print(f"[red]{for_terminal(str(exc))}[/]")
raise typer.Exit(EXIT_USAGE_ERROR)
result = validate_and_stats(data, expected_format=fmt)
@@ -130,13 +130,13 @@ def validate(
if result["issues"]:
console.print("[yellow]Issues found:[/]")
for issue in result["issues"]:
- console.print(f" [yellow]![/] {issue}")
+ console.print(f" [yellow]![/] {for_terminal(issue)}")
else:
console.print("[bold green]Dataset is valid![/]")
valid = result["valid_rows"]
total = result["total"]
- console.print(f"\n[green]{valid}/{total} rows valid for {fmt} format[/]")
+ console.print(f"\n[green]{valid}/{total} rows valid for {for_terminal(fmt)} format[/]")
if total > 0 and valid == 0:
console.print("[red]Validation failed: no usable rows remain.[/]")
diff --git a/src/soup_cli/commands/diff.py b/src/soup_cli/commands/diff.py
index 55b2fa8b..2400b581 100644
--- a/src/soup_cli/commands/diff.py
+++ b/src/soup_cli/commands/diff.py
@@ -10,6 +10,8 @@ from rich.console import Console
from rich.panel import Panel
from rich.table import Table
+from soup_cli.utils.terminal import for_terminal
+
console = Console()
@@ -103,8 +105,8 @@ def diff(
console.print(
Panel(
- f"Model A: [bold]{path_a}[/]\n"
- f"Model B: [bold]{path_b}[/]\n"
+ f"Model A: [bold]{for_terminal(path_a)}[/]\n"
+ f"Model B: [bold]{for_terminal(path_b)}[/]\n"
f"Prompts: [bold]{len(prompt_list)}[/]\n"
f"Device: [bold]{device}[/]",
title="Diff Plan",
@@ -126,7 +128,7 @@ def diff(
results = []
for idx, prompt_text in enumerate(prompt_list):
console.print(f"[bold]--- Prompt {idx + 1}/{len(prompt_list)} ---[/]")
- console.print(f"[dim]{prompt_text}[/]\n")
+ console.print(f"[dim]{for_terminal(prompt_text)}[/]\n")
messages = [{"role": "user", "content": prompt_text}]
@@ -141,14 +143,14 @@ def diff(
# Side-by-side display
panel_a = Panel(
- response_a or "[dim]<empty>[/]",
- title=f"[blue]Model A: {path_a.name}[/]",
+ for_terminal(response_a) if response_a else "[dim]<empty>[/]",
+ title=f"[blue]Model A: {for_terminal(path_a.name)}[/]",
border_style="blue",
width=console.width // 2 - 1,
)
panel_b = Panel(
- response_b or "[dim]<empty>[/]",
- title=f"[green]Model B: {path_b.name}[/]",
+ for_terminal(response_b) if response_b else "[dim]<empty>[/]",
+ title=f"[green]Model B: {for_terminal(path_b.name)}[/]",
border_style="green",
width=console.width // 2 - 1,
)
@@ -331,8 +333,8 @@ def _display_summary(results: list[dict], name_a: str, name_b: str):
table = Table(title="Comparison Summary")
table.add_column("Metric", style="bold")
- table.add_column(f"Model A ({name_a})", justify="right", style="blue")
- table.add_column(f"Model B ({name_b})", justify="right", style="green")
+ table.add_column(f"Model A ({for_terminal(name_a)})", justify="right", style="blue")
+ table.add_column(f"Model B ({for_terminal(name_b)})", justify="right", style="green")
avg_len_a = sum(r["metrics"]["len_a"] for r in results) / len(results)
avg_len_b = sum(r["metrics"]["len_b"] for r in results) / len(results)
diff --git a/src/soup_cli/commands/eval.py b/src/soup_cli/commands/eval.py
index 28e93055..c51ba805 100644
--- a/src/soup_cli/commands/eval.py
+++ b/src/soup_cli/commands/eval.py
@@ -974,9 +974,9 @@ def human(
# Display for human judgment
console.print(f"\n[bold]--- Prompt {idx + 1}/{len(prompts)} ---[/]")
- console.print(Panel(prompt_text, title="Prompt", border_style="dim"))
- console.print(Panel(resp_a, title="[blue]Response A[/]"))
- console.print(Panel(resp_b, title="[magenta]Response B[/]"))
+ console.print(Panel(for_terminal(prompt_text), title="Prompt", border_style="dim"))
+ console.print(Panel(for_terminal(resp_a), title="[blue]Response A[/]"))
+ console.print(Panel(for_terminal(resp_b), title="[magenta]Response B[/]"))
# Get human choice
while True:
diff --git a/tests/test_issue1596_rich_markup_escaping.py b/tests/test_issue1596_rich_markup_escaping.py
new file mode 100644
index 00000000..4997fbf1
--- /dev/null
+++ b/tests/test_issue1596_rich_markup_escaping.py
@@ -0,0 +1,268 @@
+"""Tests for Issue #1596: Square-bracket text in model replies and dataset keys as literal text."""
+
+import io
+import json
+import os
+import tempfile
+from pathlib import Path
+
+from rich.console import Console
+from typer.testing import CliRunner
+
+from soup_cli.cli import app as cli_app
+from soup_cli.commands import chat, data, diff
+from soup_cli.commands import eval as eval_cmd
+
+runner = CliRunner()
+ESC = "\x1b]0;t\x07"
+
+
+def test_data_inspect_columns_with_square_brackets(monkeypatch):
+ """Columns with brackets like tags[i], [x] reviewed, note[/b] should render literally
+ and strip ESC control bytes.
+ """
+ buffer = io.StringIO()
+ monkeypatch.setattr(data, "console", Console(file=buffer, color_system=None, width=400))
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir) / "keys.jsonl"
+ path.write_text(
+ json.dumps({
+ "text": "row 1",
+ f"tags[i]{ESC}": "a",
+ f"[x] reviewed{ESC}": "yes",
+ f"note[/b]{ESC}": "ok",
+ })
+ + "\n",
+ encoding="utf-8",
+ )
+ result = runner.invoke(cli_app, ["data", "inspect", str(path), "--rows", "0"])
+ assert result.exit_code == 0
+ out = buffer.getvalue()
+ assert "tags[i]" in out
+ assert "[x] reviewed" in out
+ assert "note[/b]" in out
+ assert chr(27) not in out
+
+
+def test_data_validate_unrecognized_keys_with_markup(monkeypatch):
+ """Unknown keys with brackets like notes[/b] should not trigger MarkupError
+ and should strip ESC control bytes in error reporting.
+ """
+ buffer = io.StringIO()
+ monkeypatch.setattr(data, "console", Console(file=buffer, color_system=None, width=400))
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir) / "unknown.jsonl"
+ path.write_text(
+ json.dumps({"question": "hi", f"notes[/b]{ESC}": "hello"}) + "\n",
+ encoding="utf-8",
+ )
+ result = runner.invoke(cli_app, ["data", "validate", str(path)])
+ # Exit code should be usage error (3), not unhandled MarkupError (1)
+ assert result.exit_code == 3
+ out = buffer.getvalue()
+ assert "notes[/b]" in out
+ assert chr(27) not in out
+
+
+def test_data_validate_kto_issue_with_markup(monkeypatch):
+ """KTO issue with label '[/maybe]' should not crash with MarkupError
+ and should strip ESC control bytes in issue reporting.
+ """
+ buffer = io.StringIO()
+ monkeypatch.setattr(data, "console", Console(file=buffer, color_system=None, width=400))
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ path = Path(tmpdir) / "kto.jsonl"
+ row1 = json.dumps({
+ "prompt": "p is long",
+ "completion": "c is long",
+ "label": f"[/maybe]{ESC}",
+ })
+ row2 = json.dumps({"prompt": "q is long", "completion": "d is long", "label": True})
+ path.write_text(f"{row1}\n{row2}\n", encoding="utf-8")
+ result = runner.invoke(cli_app, ["data", "validate", str(path), "--format", "kto"])
+ assert result.exit_code == 0
+ out = buffer.getvalue()
+ assert "[/maybe]" in out
+ assert chr(27) not in out
+
+
+def test_chat_replies_and_system_with_markup(monkeypatch):
+ """Assistant replies and system prompt containing brackets should render literally
+ and strip ESC bytes.
+ """
+ buffer = io.StringIO()
+ monkeypatch.setattr(chat, "console", Console(file=buffer, color_system=None, width=400))
+
+ replies = iter([
+ f"Index it as arr[i]; tick [x] when done.{ESC}",
+ f"Llama-2 wraps a turn as [INST] hi [/INST] hello.{ESC}",
+ f"Title attack: {ESC}arr[i] with ESC control byte.",
+ ])
+ monkeypatch.setattr(chat, "_load_model", lambda **kw: (None, None))
+ monkeypatch.setattr(chat, "_generate", lambda *a, **kw: next(replies))
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ fake_model = Path(tmpdir) / "fake_model"
+ fake_model.mkdir()
+ result = runner.invoke(
+ cli_app,
+ ["chat", "-m", str(fake_model), "--device", "cpu"],
+ input=f"/system Be [b]helpful[/b]!{ESC}\nq1\nq2\nq3\n/quit\n",
+ )
+ assert result.exit_code == 0
+ out = buffer.getvalue()
+ assert "arr[i]" in out
+ assert "[x]" in out
+ assert "[INST] hi [/INST]" in out
+ assert "Be [b]helpful[/b]!" in out
+ assert chr(27) not in out
+
+
+def test_diff_prompts_and_replies_with_markup(monkeypatch):
+ """Diff prompt and side-by-side panels containing markup should render literally,
+ strip ESC control bytes, and preserve raw file data.
+ """
+ buffer = io.StringIO()
+ monkeypatch.setattr(diff, "console", Console(file=buffer, color_system=None, width=400))
+
+ prompt_text = f"Check [/INST] with arr[i] and \\path{ESC}"
+ reply_a = f"A1 uses arr[i] and \\backslash [/INST]{ESC}"
+ reply_b = f"B1 closes with [/INST], arr[i] and \\foo [/code]{ESC}"
+ replies = iter([reply_a, reply_b])
+ monkeypatch.setattr(diff, "_load_model", lambda *a, **kw: (None, None))
+ monkeypatch.setattr(diff, "_generate", lambda *a, **kw: next(replies))
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ out_file = Path(tmpdir) / "diff.jsonl"
+ fake_a = Path(tmpdir) / "model_a"
+ fake_b = Path(tmpdir) / "model_b"
+ fake_a.mkdir()
+ fake_b.mkdir()
+
+ result = runner.invoke(
+ cli_app,
+ [
+ "diff",
+ "-a", str(fake_a),
+ "-b", str(fake_b),
+ "--device", "cpu",
+ "--prompt", prompt_text,
+ "-o", str(out_file),
+ ],
+ )
+ assert result.exit_code == 0
+ assert out_file.exists()
+ out = buffer.getvalue()
+ assert prompt_text.replace(ESC, "") in out
+ assert reply_a.replace(ESC, "") in out
+ assert reply_b.replace(ESC, "") in out
+ assert chr(27) not in out
+
+ # Pin written output: saved file must preserve the exact raw unescaped strings
+ content = out_file.read_text(encoding="utf-8")
+ rows = [json.loads(line) for line in content.splitlines() if line.strip()]
+ assert len(rows) == 1
+ assert rows[0]["prompt"] == prompt_text
+ assert rows[0]["response_a"] == reply_a
+ assert rows[0]["response_b"] == reply_b
+
+
+def test_diff_model_paths_and_names_with_markup(monkeypatch):
+ """Diff plan panel and summary table with brackets in model paths/names render literally."""
+ buffer = io.StringIO()
+ monkeypatch.setattr(diff, "console", Console(file=buffer, color_system=None, width=400))
+
+ monkeypatch.setattr(diff, "_load_model", lambda *a, **kw: (None, None))
+ monkeypatch.setattr(diff, "_generate", lambda *a, **kw: "reply")
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ fake_a = Path(tmpdir) / "ckpt[" / "]model[b]"
+ fake_b = Path(tmpdir) / "model[v1]"
+ fake_a.mkdir(parents=True)
+ fake_b.mkdir()
+
+ result = runner.invoke(
+ cli_app,
+ [
+ "diff",
+ "-a", str(fake_a),
+ "-b", str(fake_b),
+ "--device", "cpu",
+ "--prompt", "test",
+ ],
+ )
+ assert result.exit_code == 0
+ out = buffer.getvalue()
+ assert f"ckpt[{os.sep}]model[b]" in out
+ assert f"Model B: {fake_b}" in out
+ assert f"Model A: {fake_a.name}" in out
+ assert f"Model B: {fake_b.name}" in out
+ assert "Model A (]model[b])" in out
+ assert "Model B (model[v1])" in out
+
+
+def test_eval_human_with_markup(monkeypatch):
+ """Human eval with markup in prompt and responses should render without crash,
+ strip ESC control bytes, and save raw file data.
+ """
+ from soup_cli.eval import custom
+
+ buffer = io.StringIO()
+ monkeypatch.setattr(eval_cmd, "console", Console(file=buffer, color_system=None, width=400))
+
+ prompt_text = f"Prompt with [/INST], arr[i] and \\backslash [/tag]{ESC}"
+ reply_a = f"A1 with arr[i], [/INST] and \\slash{ESC}"
+ reply_b = f"B1 with [/INST] tags, arr[i] and \\test{ESC}"
+ replies = {
+ "model_a": iter([reply_a]),
+ "model_b": iter([reply_b]),
+ }
+ monkeypatch.setattr(
+ custom,
+ "_create_default_generator",
+ lambda path: (lambda prompt: next(replies[Path(path).name])),
+ )
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ prompts_file = Path(tmpdir) / "prompts.jsonl"
+ out_file = Path(tmpdir) / "judgments.json"
+ prompts_file.write_text(
+ json.dumps({"prompt": prompt_text}) + "\n",
+ encoding="utf-8",
+ )
+ fake_a = Path(tmpdir) / "model_a"
+ fake_b = Path(tmpdir) / "model_b"
+ fake_a.mkdir()
+ fake_b.mkdir()
+
+ monkeypatch.setattr(eval_cmd.console, "input", lambda *a: "a")
+
+ result = runner.invoke(
+ cli_app,
+ [
+ "eval",
+ "human",
+ "-i", str(prompts_file),
+ "-a", str(fake_a),
+ "-b", str(fake_b),
+ "-o", str(out_file),
+ ],
+ )
+ assert result.exit_code == 0
+ assert out_file.exists()
+ out = buffer.getvalue()
+ assert prompt_text.replace(ESC, "") in out
+ assert reply_a.replace(ESC, "") in out
+ assert reply_b.replace(ESC, "") in out
+ assert chr(27) not in out
+
+ # Pin written output: saved file must preserve the exact raw unescaped strings
+ data = json.loads(out_file.read_text(encoding="utf-8"))
+ assert len(data["judgments"]) == 1
+ j = data["judgments"][0]
+ assert j["prompt"] == prompt_text
+ assert j["response_a"] == reply_a
+ assert j["response_b"] == reply_b