amitbhatt6075 commited on
Commit
0bcdbd1
·
1 Parent(s): 3b4140e

fix: Implement robust parser for LLM response to fix JSON errors

Browse files
Files changed (1) hide show
  1. core/thunderbird_engine.py +29 -5
core/thunderbird_engine.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import pandas as pd
3
  import joblib
4
  import json
@@ -105,17 +106,40 @@ def predict_niche_trends() -> dict:
105
  return {"trend_predictions": {}}
106
 
107
  def decode_market_trend(topic: str, llm_instance) -> Dict[str, str]:
108
- """Decodes a keyword into a strategy with a clear failure message."""
 
 
 
 
 
109
  offline_response = {"summary": "AI Analyst is currently offline.", "impact": "Could not get real-time analysis.", "strategy": "Please try again later."}
110
  if not llm_instance: return offline_response
 
111
  today_date = datetime.now().strftime("%Y-%m-%d")
112
- prompt = f"[INST]You are PulseAI, a Strategy Director. Today is {today_date}. Analyze trend: \"{topic}\". Provide JSON with keys: \"summary\", \"impact\", \"strategy\".[/INST]"
 
 
 
 
 
 
 
113
  try:
114
  response = llm_instance(prompt, max_tokens=256, temperature=0.6, echo=False)
115
  text = response['choices'][0]['text'].strip()
116
- start, end = text.find('{'), text.rfind('}') + 1
117
- if start != -1 and end != 0: return json.loads(text[start:end])
118
- else: raise ValueError("Invalid JSON from LLM")
 
 
 
 
 
 
 
 
 
 
119
  except Exception as e:
120
  print(f" - ❌ LLM Error: {e}")
121
  return offline_response
 
1
  import os
2
+ import re
3
  import pandas as pd
4
  import joblib
5
  import json
 
106
  return {"trend_predictions": {}}
107
 
108
  def decode_market_trend(topic: str, llm_instance) -> Dict[str, str]:
109
+ """
110
+ Decodes a keyword into a strategy.
111
+ This version is ROBUST and can parse messy, non-JSON output from the LLM.
112
+ """
113
+ print(f"🧠 [Thunderbird] Decoding Trend with ROBUST parser: {topic}")
114
+
115
  offline_response = {"summary": "AI Analyst is currently offline.", "impact": "Could not get real-time analysis.", "strategy": "Please try again later."}
116
  if not llm_instance: return offline_response
117
+
118
  today_date = datetime.now().strftime("%Y-%m-%d")
119
+ prompt = f"""[INST]
120
+ You are PulseAI, a Strategy Director. Today is {today_date}. Analyze trend: "{topic}".
121
+ Provide a briefing with 3 parts:
122
+ 1. SUMMARY: [A sharp sentence explaining what's happening now]
123
+ 2. IMPACT: [A sentence on why this matters for a brand's revenue or reach]
124
+ 3. STRATEGY: [One creative, specific content idea an agency can execute this week]
125
+ [/INST]"""
126
+
127
  try:
128
  response = llm_instance(prompt, max_tokens=256, temperature=0.6, echo=False)
129
  text = response['choices'][0]['text'].strip()
130
+
131
+ # === THE FIX: ROBUST PARSING INSTEAD OF JSON ===
132
+ summary = re.search(r"SUMMARY:\s*(.*)", text, re.IGNORECASE)
133
+ impact = re.search(r"IMPACT:\s*(.*)", text, re.IGNORECASE)
134
+ strategy = re.search(r"STRATEGY:\s*(.*)", text, re.IGNORECASE)
135
+
136
+ return {
137
+ "summary": summary.group(1).strip() if summary else "AI analysis is currently being refined.",
138
+ "impact": impact.group(1).strip() if impact else "The market impact is under evaluation.",
139
+ "strategy": strategy.group(1).strip() if strategy else "Awaiting actionable strategy from AI."
140
+ }
141
+ # === END OF FIX ===
142
+
143
  except Exception as e:
144
  print(f" - ❌ LLM Error: {e}")
145
  return offline_response