Heuristic:24mlight A Share investment Agent LLM JSON Parsing Fallback
| 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:
- Try
json.loads(raw_text)directly. - If that fails, strip
```json ... ```code fences with regex and retry. - If that fails, extract the substring between the first
{and last}and retry. - If JSON parsing fails entirely, use regex (
r"-?\d+(\.\d+)?") to extract a numeric score as fallback.
- Try
- 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
- Implementation:24mlight_A_Share_investment_Agent_portfolio_management_agent
- Implementation:24mlight_A_Share_investment_Agent_sentiment_agent
- Implementation:24mlight_A_Share_investment_Agent_get_stock_news
- Implementation:24mlight_A_Share_investment_Agent_Backtester
- Principle:24mlight_A_Share_investment_Agent_Unified_LLM_Gateway
- Principle:24mlight_A_Share_investment_Agent_Portfolio_Decision_Synthesis