Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(pattern): return a JSON error for malformed tool arguments instead of raising (#1923)

Rudy Mizrahi Celekli7812c4c119a7
diff --git a/agent/src/tools/pattern_tool.py b/agent/src/tools/pattern_tool.py
index 59ff13abf..e6d6ed6e0 100644
--- a/agent/src/tools/pattern_tool.py
+++ b/agent/src/tools/pattern_tool.py
@@ -410,9 +410,41 @@ class PatternTool(BaseTool):
repeatable = True
def execute(self, **kwargs) -> str:
- """Run pattern detection."""
- return run_pattern(
- run_dir=kwargs["run_dir"],
- patterns=kwargs.get("patterns", "all"),
- window=kwargs.get("window", 10),
- )
+ """Run pattern detection.
+
+ Model-supplied arguments are normalised first: an explicit JSON ``null``
+ means "use the default", ``patterns`` may be a list, and ``window`` must
+ be an integer (a numeric string is accepted). Anything else is reported
+ as a JSON error instead of raising out of the tool.
+ """
+ run_dir = kwargs.get("run_dir")
+ if not isinstance(run_dir, str) or not run_dir.strip():
+ return json.dumps({"status": "error", "error": "run_dir is required"}, ensure_ascii=False)
+
+ patterns = kwargs.get("patterns")
+ if patterns is None or patterns == "":
+ patterns = "all"
+ elif isinstance(patterns, (list, tuple)):
+ patterns = ",".join(str(p) for p in patterns)
+ elif not isinstance(patterns, str):
+ return json.dumps(
+ {"status": "error", "error": "patterns must be a string or a list of names"},
+ ensure_ascii=False,
+ )
+
+ window_raw = kwargs.get("window")
+ if window_raw is None or window_raw == "":
+ window = 10
+ else:
+ try:
+ if isinstance(window_raw, bool) or isinstance(window_raw, (list, dict)):
+ raise ValueError
+ if isinstance(window_raw, float) and not window_raw.is_integer():
+ raise ValueError
+ window = int(window_raw)
+ except (TypeError, ValueError, OverflowError):
+ return json.dumps(
+ {"status": "error", "error": f"window must be an integer, got {window_raw!r}"},
+ ensure_ascii=False,
+ )
+ return run_pattern(run_dir=run_dir, patterns=patterns, window=window)
diff --git a/agent/tests/test_pattern_tool_argument_coercion.py b/agent/tests/test_pattern_tool_argument_coercion.py
new file mode 100644
index 000000000..1ceacccf3
--- /dev/null
+++ b/agent/tests/test_pattern_tool_argument_coercion.py
@@ -0,0 +1,66 @@
+"""``PatternTool`` must turn malformed LLM arguments into JSON, not exceptions."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pandas as pd
+import pytest
+
+from src.tools.pattern_tool import PatternTool
+
+
+def run_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))
+ arts = tmp_path / "artifacts"
+ arts.mkdir()
+ idx = pd.date_range("2024-01-01", periods=40)
+ close = [10 + (i % 7) for i in range(40)]
+ pd.DataFrame(
+ {"open": close, "high": [c + 1 for c in close], "low": [c - 1 for c in close], "close": close},
+ index=idx,
+ ).to_csv(arts / "ohlcv_AAA.csv")
+ return tmp_path
+
+
+def _run(run_dir: Path, **kwargs):
+ return json.loads(PatternTool().execute(run_dir=str(run_dir), **kwargs))
+
+
+def test_null_window_uses_default(run_dir: Path) -> None:
+ out = _run(run_dir, patterns="peaks_valleys", window=None)
+ assert out["status"] == "ok"
+ assert out["window"] == 10
+
+
+def test_numeric_string_window_is_accepted(run_dir: Path) -> None:
+ out = _run(run_dir, patterns="peaks_valleys", window="3")
+ assert out["status"] == "ok"
+ assert out["window"] == 3
+
+
[email protected]("bad", ["abc", 2.5, True, [3]])
+def test_non_integer_window_is_a_json_error(run_dir: Path, bad) -> None:
+ out = _run(run_dir, patterns="peaks_valleys", window=bad)
+ assert out["status"] == "error"
+ assert "window" in out["error"]
+
+
+def test_patterns_list_is_accepted(run_dir: Path) -> None:
+ out = _run(run_dir, patterns=["peaks_valleys", "trend_slope"], window=3)
+ assert out["status"] == "ok"
+ assert out["patterns"] == ["peaks_valleys", "trend_slope"]
+
+
+def test_null_patterns_means_all(run_dir: Path) -> None:
+ out = _run(run_dir, patterns=None, window=3)
+ assert out["status"] == "ok"
+ assert len(out["patterns"]) == 8
+
+
+def test_missing_run_dir_is_a_json_error() -> None:
+ out = json.loads(PatternTool().execute())
+ assert out["status"] == "error"
+ assert "run_dir" in out["error"]