HKUDS/Vibe-Trading · error · ValueError
malformed expression: {exc}
Error message
malformed expression: {exc} What it means
_safe_arith parses the expression with ast.parse(mode='eval'); a SyntaxError is wrapped into this ValueError so callers get a uniform validation exception. It fires before any evaluation, purely on unparseable input such as unbalanced parentheses or empty/garbage strings.
Source
Thrown at agent/src/tools/financial_rigor_tool.py:135
The expression is parsed and evaluated recursively with Decimal arithmetic,
so ``0.1 + 0.2`` is exactly ``0.3`` — no IEEE-754 drift, and no ``eval``.
Only numbers and the operators ``+ - * /`` (with optional unary sign) are
permitted; any other AST node raises ``ValueError``.
Args:
expr: Arithmetic expression string, e.g. ``"510 * 9.11e9"``.
Returns:
The exact Decimal result.
Raises:
ValueError: If the expression is malformed or contains a disallowed
element.
"""
try:
tree = ast.parse(expr, mode="eval")
except SyntaxError as exc:
raise ValueError(f"malformed expression: {exc}") from exc
return _eval_arith_node(tree.body)
# ---------------------------------------------------------------------------
# Core verification routines (pure, return structured dicts, no I/O)
# ---------------------------------------------------------------------------
def verify_market_cap(
price: Any, shares: Any, reported_cap: Any, currency: str = "",
) -> dict[str, Any]:
"""Verify ``market cap = price × shares`` against a reported value.
Args:
price: Current share price.
shares: Total share count.
reported_cap: The market-cap figure being checked.
currency: Optional currency label for display only.
View on GitHub (pinned to 80ffdda44c)
Solutions
- Sanitize the input (strip commas/currency symbols, normalize quotes) before calling
- Validate the expression with ast.parse in the caller for a cleaner upstream error
- Retry with a corrected expression when the tool reports a parse failure
Example fix
# before
exact_calc("1,000 * 0.05")
# after
exact_calc("1000 * 0.05") Defensive patterns
Strategy: validation
Validate before calling
import ast
expr = user_input.replace(",", "").replace("$", "")
try:
ast.parse(expr, mode="eval")
except SyntaxError as e:
raise ValueError(f"bad formula at col {e.offset}: {e.msg}") from e Try / catch
try:
value = _safe_arith(expr)
except ValueError as e:
if str(e).startswith("malformed expression"):
return None / re-ask user for a corrected formula
raise Prevention
- Normalize input: strip commas, currency symbols, smart quotes
- ast.parse upstream for clearer error positions
- Never pass empty strings; short-circuit to Decimal(0)
When it happens
Trigger: Calling exact_calc or _safe_arith with '', '2 +', '(1+2', or non-Python text like 'two plus two'.
Common situations: User-typed formulas, truncated LLM output, or copy-paste artifacts (smart quotes, thousand separators like '1,000')
Understand the failure class
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Related errors
- unsupported operator: {type(node.op).__name__}
- unsupported unary operator: {type(node.op).__name__}
- invalid alpha_id
- alpha_id not found
- invalid period: {exc}
AI-assisted analysis of HKUDS/Vibe-Trading@80ffdda44c (2026-08-28).
Data as JSON: /api/errors/effa8584b5c13f5f.
Report an issue: GitHub.