Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(data): repair and check nested and documented-shape tool calls in soup data clean (#1338) (#1453)
Abdulwaarith Zakariyya452bfa1f2b77
diff --git a/changelog.d/0.75.1/1453.fixed.md b/changelog.d/0.75.1/1453.fixed.mdnew file mode 100644index 00000000..249bb860--- /dev/null+++ b/changelog.d/0.75.1/1453.fixed.md@@ -0,0 +1 @@+- **`soup data clean --repair-json` and `--drop-invalid-json` missed nested tool calls and dropped valid documented-shape rows (#1338 by @abdulwaarith0 in #1453).** Both flags read only a flat `arguments` key on the row's top-level `tool_calls`, so calls inside an assistant turn (what `soup agent synth` writes, and the OpenAI fine-tuning shape) were never repaired or checked, and a valid `{"function": {"arguments": ...}}` call read as `""` and got its row dropped. They now read every call the tool-calling loader reads, in both shapes, and leave dict arguments alone. A `tool-calling` row with no top-level `tool_calls` no longer gets an empty list added, so the report stops counting it under "Format Normalization".diff --git a/docs/data.md b/docs/data.mdindex a495d9f2..bc624552 100644--- a/docs/data.md+++ b/docs/data.md@@ -110,6 +110,9 @@ soup data clean raw_data.jsonl --strip-boilerplate --repair-code --repair-json -2. `--repair-code`: Auto-closes unclosed triple backtick (```` ``` ````) code fences in assistant completions.3. `--repair-json`: Unwraps markdown code blocks from JSON arguments and repairs trailing commas in tool calls.4. `--prune-echo`: Drops rows where the assistant merely repeats the user prompt verbatim.+ 5. `--drop-invalid-json`: Drops rows with a tool call whose arguments still do not parse as JSON (after `--repair-json`, when both are set).++ `--repair-json` and `--drop-invalid-json` read every call the tool-calling loader reads: the row's top-level `tool_calls` and each assistant turn's `tool_calls`, in the documented `{"function": {"name": ..., "arguments": ...}}` shape or flat. Arguments given as a JSON object are left as they are.Supports all standard formats: `chatml`, `alpaca`, `sharegpt`, `dpo`, `kto`, and `tool-calling`.diff --git a/src/soup_cli/utils/data_clean.py b/src/soup_cli/utils/data_clean.pyindex a717d0bd..f04c991d 100644--- a/src/soup_cli/utils/data_clean.py+++ b/src/soup_cli/utils/data_clean.py@@ -169,6 +169,94 @@ def is_echo_turn(prompt: str, response: str) -> bool:return clean_p == clean_r+def _clean_arguments(+ args: str, applied_rules: List[str], repair_json: bool, drop_invalid_json: bool+) -> Optional[str]:+ """Sanitize (and optionally repair) one call's JSON-string arguments.++ Returns None when ``drop_invalid_json`` is set and the result does not parse.+ """+ san_args, was_san = sanitize_text(args)+ if was_san:+ applied_rules.append("Invisible & Control Chars")+ if repair_json:+ repaired_args, was_repaired = repair_json_string(san_args)+ if was_repaired:+ applied_rules.append("Malformed JSON in Tools")+ return repaired_args+ if drop_invalid_json:+ try:+ json.loads(san_args)+ except (json.JSONDecodeError, ValueError):+ return None+ return san_args+++def _clean_tool_calls(+ tool_calls: Any, applied_rules: List[str], repair_json: bool, drop_invalid_json: bool+) -> Any:+ """Clean the ``arguments`` of every call in a ``tool_calls`` list.++ A call carries its arguments either in the documented ``function`` shape+ (``{"function": {"name": ..., "arguments": ...}}``, what the tool-calling+ loader reads) or flat (``{"name": ..., "arguments": ...}``). Arguments given+ as a dict are already parsed and left alone, and a ``function`` call with no+ ``arguments`` is left alone too, since the loader reads it as ``{}``.++ Returns None when ``drop_invalid_json`` is set and a call does not parse.+ Anything that is not a list, or a call that is not a dict, is passed through.+ Since None means "drop the row", callers skip a ``tool_calls`` of None (the+ loader reads it as no calls) instead of passing it here.+ """+ if not isinstance(tool_calls, list):+ return tool_calls+ cleaned_calls: List[Any] = []+ for call in tool_calls:+ if not isinstance(call, dict):+ cleaned_calls.append(call)+ continue+ c = dict(call)+ func = c.get("function")+ if isinstance(func, dict):+ args = func.get("arguments")+ if isinstance(args, str):+ cleaned_args = _clean_arguments(+ args, applied_rules, repair_json, drop_invalid_json+ )+ if cleaned_args is None:+ return None+ c["function"] = {**func, "arguments": cleaned_args}+ else:+ args = c.get("arguments", "")+ if isinstance(args, str):+ cleaned_args = _clean_arguments(+ args, applied_rules, repair_json, drop_invalid_json+ )+ if cleaned_args is None:+ return None+ c["arguments"] = cleaned_args+ cleaned_calls.append(c)+ return cleaned_calls+++def _clean_turn_tool_calls(+ msg: Dict[str, Any], applied_rules: List[str], repair_json: bool, drop_invalid_json: bool+) -> bool:+ """Clean the calls an assistant turn carries, in place on ``msg`` (a copy).++ Returns False when ``drop_invalid_json`` is set and a call does not parse.+ """+ if msg.get("role") != "assistant" or msg.get("tool_calls") is None:+ return True+ cleaned_calls = _clean_tool_calls(+ msg["tool_calls"], applied_rules, repair_json, drop_invalid_json+ )+ if cleaned_calls is None:+ return False+ msg["tool_calls"] = cleaned_calls+ return True++def clean_row(row: Dict[str, Any],fmt: str,@@ -190,39 +278,12 @@ def clean_row(if fmt == "tool-calling" or "tool_calls" in row:cleaned_row = dict(row)- tool_calls = row.get("tool_calls", [])- if isinstance(tool_calls, list):- cleaned_calls: List[Dict[str, Any]] = []- for call in tool_calls:- if not isinstance(call, dict):- cleaned_calls.append(call)- continue- c = dict(call)- args = c.get("arguments", "")- if isinstance(args, str):- san_args, was_san = sanitize_text(args)- if was_san:- applied_rules.append("Invisible & Control Chars")- if repair_json:- repaired_args, was_repaired = repair_json_string(san_args)- if was_repaired:- applied_rules.append("Malformed JSON in Tools")- c["arguments"] = repaired_args- else:- c["arguments"] = san_args- if drop_invalid_json:- try:- json.loads(san_args)- except (json.JSONDecodeError, ValueError):- return None, ["Invalid JSON in Tool Calls"]- else:- c["arguments"] = san_args- if drop_invalid_json:- try:- json.loads(san_args)- except (json.JSONDecodeError, ValueError):- return None, ["Invalid JSON in Tool Calls"]- cleaned_calls.append(c)+ if row.get("tool_calls") is not None:+ cleaned_calls = _clean_tool_calls(+ row["tool_calls"], applied_rules, repair_json, drop_invalid_json+ )+ if cleaned_calls is None:+ return None, ["Invalid JSON in Tool Calls"]cleaned_row["tool_calls"] = cleaned_callsif "messages" in row and isinstance(row["messages"], list):@@ -238,6 +299,8 @@ def clean_row(if was_san:applied_rules.append("Invisible & Control Chars")m["content"] = san_c+ if not _clean_turn_tool_calls(m, applied_rules, repair_json, drop_invalid_json):+ return None, ["Invalid JSON in Tool Calls"]cleaned_messages.append(m)cleaned_row["messages"] = cleaned_messages@@ -288,6 +351,8 @@ def clean_row(msg["content"] = sanitized_contentelse:msg["content"] = sanitized_content+ if not _clean_turn_tool_calls(msg, applied_rules, repair_json, drop_invalid_json):+ return None, ["Invalid JSON in Tool Calls"]cleaned_messages.append(msg)if not any(isinstance(m, dict) and m.get("role") == "assistant" for m in cleaned_messages):diff --git a/tests/test_issue1338_clean_nested_tool_calls.py b/tests/test_issue1338_clean_nested_tool_calls.pynew file mode 100644index 00000000..8b60f1e3--- /dev/null+++ b/tests/test_issue1338_clean_nested_tool_calls.py@@ -0,0 +1,248 @@+"""#1338: `soup data clean` repairs and checks every tool call the loader reads.++The tool-calling loader reads calls in the documented ``function`` shape, both at+the row's top level and inside each assistant turn (#1217). ``clean_row`` used to+read only a flat ``arguments`` key on the top-level list, so nested calls were+never repaired or checked, and a valid documented-shape row had its missing flat+``arguments`` parsed as ``""`` and was dropped.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest+from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.data.formats import format_to_messages+from soup_cli.utils.data_clean import clean_dataset, clean_row++BROKEN = '```json\n{"city": "Paris",}\n```' # fenced, trailing comma+REPAIRED = '{"city": "Paris"}'+UNREPAIRABLE = '{"city": "Paris"'+TOOLS = [{"type": "function", "function": {"name": "get_weather", "parameters": {}}}]+++def _call(args):+ return {"id": "call_0", "type": "function",+ "function": {"name": "get_weather", "arguments": args}}+++def _nested_row(args):+ """A call inside the assistant turn, no top-level keys (``soup agent synth``)."""+ return {"messages": [{"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "tool_calls": [_call(args)]}]}+++def _openai_row(args):+ """The OpenAI fine-tuning shape."""+ return {"messages": [{"role": "user", "content": "Weather in Paris?"},+ {"role": "assistant", "content": None, "tool_calls": [_call(args)]},+ {"role": "tool", "tool_call_id": "call_0", "content": "21"},+ {"role": "assistant", "content": "21 C."}],+ "tools": TOOLS}+++def _top_level_row(args):+ """The documented shape, calls at the row's top level."""+ return {"messages": [{"role": "user", "content": "Weather in Paris?"}],+ "tools": TOOLS, "tool_calls": [_call(args)]}+++def _flat_row(args):+ """The flat shape the existing tests use: the control."""+ return {"messages": [{"role": "user", "content": "Weather in Paris?"}],+ "tool_calls": [{"name": "get_weather", "arguments": args}]}+++def _all_args(row):+ """Every call's arguments in the row, nested first, in order."""+ out = []+ for msg in row.get("messages", []):+ for c in msg.get("tool_calls") or []:+ out.append(c["function"]["arguments"])+ for c in row.get("tool_calls", []):+ out.append(c["function"]["arguments"] if "function" in c else c["arguments"])+ return out+++SHAPES = {+ "nested": (_nested_row, "chatml"),+ "openai": (_openai_row, "tool-calling"),+ "top_level": (_top_level_row, "tool-calling"),+ "flat": (_flat_row, "tool-calling"),+}++[email protected]("shape", list(SHAPES))+class TestRepairJson:+ def test_repairs_the_call(self, shape):+ make, fmt = SHAPES[shape]+ cleaned, rules = clean_row(make(BROKEN), fmt, repair_json=True)+ assert cleaned is not None+ assert _all_args(cleaned) == [REPAIRED]+ assert "Malformed JSON in Tools" in rules++ def test_leaves_the_call_alone_without_the_flag(self, shape):+ make, fmt = SHAPES[shape]+ cleaned, rules = clean_row(make(BROKEN), fmt)+ assert _all_args(cleaned) == [BROKEN]+ assert "Malformed JSON in Tools" not in rules++ def test_keeps_the_other_call_keys(self, shape):+ if shape == "flat":+ pytest.skip("the flat call has no function dict")+ make, fmt = SHAPES[shape]+ cleaned, _ = clean_row(make(BROKEN), fmt, repair_json=True)+ calls = [c for m in cleaned["messages"] for c in (m.get("tool_calls") or [])]+ calls += cleaned.get("tool_calls", [])+ assert calls == [_call(REPAIRED)]++ def test_does_not_mutate_the_input(self, shape):+ make, fmt = SHAPES[shape]+ row = make(BROKEN)+ before = json.dumps(row, sort_keys=True)+ clean_row(row, fmt, repair_json=True)+ assert json.dumps(row, sort_keys=True) == before++[email protected]("shape", list(SHAPES))+class TestDropInvalidJson:+ def test_keeps_a_valid_row(self, shape):+ make, fmt = SHAPES[shape]+ cleaned, rules = clean_row(make(REPAIRED), fmt, drop_invalid_json=True)+ assert cleaned is not None, rules+ assert _all_args(cleaned) == [REPAIRED]++ def test_drops_an_invalid_row(self, shape):+ make, fmt = SHAPES[shape]+ cleaned, rules = clean_row(make(UNREPAIRABLE), fmt, drop_invalid_json=True)+ assert cleaned is None+ assert rules == ["Invalid JSON in Tool Calls"]++ def test_repair_runs_before_the_check(self, shape):+ make, fmt = SHAPES[shape]+ cleaned, _ = clean_row(make(BROKEN), fmt, repair_json=True, drop_invalid_json=True)+ assert cleaned is not None+ assert _all_args(cleaned) == [REPAIRED]++ def test_drops_what_repair_cannot_fix(self, shape):+ make, fmt = SHAPES[shape]+ cleaned, rules = clean_row(+ make(UNREPAIRABLE), fmt, repair_json=True, drop_invalid_json=True+ )+ assert cleaned is None+ assert rules == ["Invalid JSON in Tool Calls"]++[email protected]("shape", ["nested", "openai", "top_level"])+def test_every_row_kept_by_drop_invalid_json_loads(shape):+ """The rows ``--drop-invalid-json`` keeps are the rows the loader accepts."""+ make, fmt = SHAPES[shape]+ for args in (REPAIRED, UNREPAIRABLE):+ row = make(args)+ cleaned, _ = clean_row(row, fmt, drop_invalid_json=True)+ loads = format_to_messages(row, "tool-calling") is not None+ assert (cleaned is not None) == loads+++def test_dict_arguments_are_left_alone():+ row = _top_level_row({"city": "Paris"})+ cleaned, rules = clean_row(row, "tool-calling", repair_json=True, drop_invalid_json=True)+ assert cleaned == row+ assert rules == []+++def test_a_function_call_without_arguments_is_kept():+ """The loader reads a missing ``arguments`` as ``{}``."""+ row = _top_level_row("{}")+ del row["tool_calls"][0]["function"]["arguments"]+ assert format_to_messages(row, "tool-calling") is not None+ cleaned, _ = clean_row(row, "tool-calling", drop_invalid_json=True)+ assert cleaned == row+++def test_a_later_invalid_nested_call_drops_the_row():+ row = _openai_row(REPAIRED)+ row["messages"].append({"role": "assistant", "tool_calls": [_call(UNREPAIRABLE)]})+ cleaned, rules = clean_row(row, "tool-calling", drop_invalid_json=True)+ assert cleaned is None+ assert rules == ["Invalid JSON in Tool Calls"]+++def test_calls_outside_an_assistant_turn_are_not_touched():+ """The loader only reads calls on assistant turns."""+ row = _nested_row(REPAIRED)+ row["messages"][0]["tool_calls"] = [_call(UNREPAIRABLE)]+ cleaned, _ = clean_row(row, "chatml", drop_invalid_json=True)+ assert cleaned == row+++def test_a_nested_call_row_gains_no_top_level_tool_calls():+ row = _openai_row(REPAIRED)+ cleaned, rules = clean_row(row, "tool-calling")+ assert "tool_calls" not in cleaned+ assert cleaned == row+ assert rules == []+++ "flags",+ [{}, {"repair_json": True}, {"drop_invalid_json": True}],+ ids=["none", "repair", "drop"],+)+def test_a_null_top_level_tool_calls_is_kept(flags):+ """The loader reads ``"tool_calls": null`` as no calls (``top_level_calls is None``)."""+ row = {+ "messages": [+ {"role": "user", "content": "hi"},+ {"role": "assistant", "content": "hello"},+ ],+ "tools": TOOLS,+ "tool_calls": None,+ }+ assert format_to_messages(row, "tool-calling") is not None+ cleaned, rules = clean_row(row, "tool-calling", **flags)+ assert cleaned == row, rules+ assert rules == []+++def test_nested_control_chars_are_sanitised():+ row = _nested_row('{"city": "Paris"}')+ cleaned, rules = clean_row(row, "chatml")+ assert _all_args(cleaned) == [REPAIRED]+ assert "Invisible & Control Chars" in rules+++def test_clean_dataset_counts_the_nested_repair():+ rows = [_nested_row(BROKEN), _nested_row(REPAIRED)]+ cleaned, report = clean_dataset(rows, "chatml", repair_json=True)+ assert [_all_args(r) for r in cleaned] == [[REPAIRED], [REPAIRED]]+ assert report.total_modified == 1+ assert report.total_clean == 1+++def test_the_issue_repro_end_to_end(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ rows = [_nested_row(BROKEN), _openai_row(BROKEN), _top_level_row(BROKEN)]+ Path("raw.jsonl").write_text(+ "".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8"+ )+ runner = CliRunner()+ result = runner.invoke(+ app, ["data", "clean", "raw.jsonl", "-o", "clean.jsonl", "-f", "--repair-json"]+ )+ assert result.exit_code == 0, result.output+ out = [json.loads(line) for line in Path("clean.jsonl").read_text().splitlines()]+ assert [_all_args(r) for r in out] == [[REPAIRED]] * 3+ for row in out:+ assert format_to_messages(row, "tool-calling") is not None++ Path("raw.jsonl").write_text(json.dumps(_top_level_row(REPAIRED)) + "\n", encoding="utf-8")+ result = runner.invoke(+ app, ["data", "clean", "raw.jsonl", "-o", "clean.jsonl", "-f", "--drop-invalid-json"]+ )+ assert result.exit_code == 0, result.output+ assert len(Path("clean.jsonl").read_text().splitlines()) == 1