Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:24mlight A Share investment Agent LLM JSON Parsing Fallback

From Leeroopedia
Knowledge Sources
Domains LLMs, Debugging, Finance
Last Updated 2026-10-10 14:00 GMT

Overview

Multi-layer JSON extraction strategy to robustly parse LLM-generated JSON responses that may include code fences, extra text, or malformed formatting.

Description

LLMs frequently wrap JSON responses in Markdown code fences (```json ... ```), prepend explanatory text, or produce slightly malformed JSON. This heuristic implements a cascading fallback parser: first attempt json.loads() on the raw text; if that fails, strip code fences and retry; if that fails, find the outermost {...} braces and parse the substring; if all JSON parsing fails, fall back to regex number extraction for sentiment scores.

Usage

Use this heuristic whenever parsing LLM output that is expected to contain structured JSON. This applies to:

  • Portfolio manager decisions (action, quantity, reasoning)
  • Sentiment agent scores (score, signal, confidence)
  • Backtester decision extraction from agent responses
  • Any agent that calls get_chat_completion() and expects JSON back

The Insight (Rule of Thumb)

  • Action: Implement a 4-tier fallback parser for LLM JSON output:
    1. Try json.loads(raw_text) directly.
    2. If that fails, strip ```json ... ``` code fences with regex and retry.
    3. If that fails, extract the substring between the first { and last } and retry.
    4. If JSON parsing fails entirely, use regex (r"-?\d+(\.\d+)?") to extract a numeric score as fallback.
  • Value: N/A (pattern, not a configuration value).
  • Trade-off: Slightly more complex parsing code vs. dramatically higher robustness against LLM output variability.
  • Compatibility: Works with any LLM provider (Gemini, OpenAI-compatible); the pattern is provider-agnostic.

Reasoning

LLMs are non-deterministic in their output formatting. Even with explicit instructions to "return only JSON," models frequently add:

  • Markdown code fences (```json)
  • Explanatory text before/after the JSON
  • Slightly malformed JSON (trailing commas, unquoted keys)

In production, a single json.loads() call fails on a significant fraction of responses, causing agents to crash or return error signals. The cascading fallback ensures that valid JSON buried in extra text is still extracted. The final regex fallback for numeric scores ensures that even completely unparseable responses produce a usable sentiment value rather than crashing the pipeline.

Code Evidence

Code fence stripping and brace extraction from src/agents/portfolio_manager.py:63-86:

def _parse_decision_json(raw_text: str) -> Dict[str, Any]:
    if raw_text is None:
        raise ValueError("LLM returned None for portfolio decision")
    text = raw_text.strip()
    if not text:
        raise ValueError("LLM returned empty string for portfolio decision")
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        # Remove surrounding code fences like ```json ... ```
        if text.startswith("```"):
            fence_match = re.match(r"```(?:json)?\s*(.+?)\s*```", text, re.DOTALL | re.IGNORECASE)
            if fence_match:
                candidate = fence_match.group(1).strip()
                try:
                    return json.loads(candidate)
                except json.JSONDecodeError:
                    text = candidate  # continue with fallback extraction
        start = text.find("{")
        end = text.rfind("}")
        if start != -1 and end != -1 and end > start:
            candidate = text[start : end + 1]
            return json.loads(candidate)
    raise ValueError("Unable to parse LLM decision JSON")

Regex number fallback from src/tools/news_crawler.py:292-320:

# 回退到数字解析
match = re.search(r"-?\d+(\.\d+)?", preview.replace("%", " "))
if match:
    score = max(-1.0, min(1.0, float(match.group())))
    return {
        "score": score,
        "signal": "bullish" if score >= 0.3 else ("bearish" if score <= -0.3 else "neutral"),
        "confidence": abs(score),
        "reasoning": "",
    }

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment