portiq-backend / modules /api_caller.py
Ramkumar Shanmugam
fix(ui): sync Today's Briefing banner on import and update BUY score scoring
e06f207
Raw History Blame Contribute Delete
26.7 kB
"""Module for interacting with the Gemini API for AI and Search Grounding."""
import os
import json
import time
from datetime import datetime
from dotenv import load_dotenv
from google import genai
from google.genai import types
# 1. Load the GEMINI_API_KEY from the .env file
load_dotenv()
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
def build_tcr_prompt(*args, **kwargs) -> str:
"""
Builds the upgraded, bounded PortIQ persona prompt with pre-computed fundamentals,
strict search budget (max 4 queries), falling knife decision engine, and JSON output specification.
Supports both signatures:
build_tcr_prompt(today_date, portfolio_text, strategy_context, news_instructions)
build_tcr_prompt(portfolio_text, today_date, strategy_context, include_news=False)
"""
import re
# Unpack args flexibly
arg1 = args[0] if len(args) > 0 else kwargs.get("today_date") or kwargs.get("portfolio_text")
arg2 = args[1] if len(args) > 1 else kwargs.get("portfolio_text") or kwargs.get("today_date")
arg3 = args[2] if len(args) > 2 else kwargs.get("strategy_context", "")
arg4 = args[3] if len(args) > 3 else kwargs.get("news_instructions")
# Check if first positional argument is a date (YYYY-MM-DD)
if isinstance(arg1, str) and re.match(r'^\d{4}-\d{2}-\d{2}$', arg1.strip()):
today_date = arg1.strip()
portfolio_text = arg2 or ""
strategy_context = arg3 or ""
news_instructions = arg4
else:
portfolio_text = arg1 or ""
today_date = str(arg2).strip() if (arg2 and re.match(r'^\d{4}-\d{2}-\d{2}$', str(arg2).strip())) else datetime.now().strftime("%Y-%m-%d")
strategy_context = arg3 or ""
news_instructions = arg4
include_news = kwargs.get("include_news", False)
if not news_instructions:
if include_news:
news_instructions = """1. Search for real-time news for the stocks in the portfolio. Prioritize top 10-12 stocks with significant recent developments.
2. For each selected stock, headline must be 60-80 words detailing what happened, why it matters, and direct impact on Ram's position.
3. Search for today's Nifty, Sensex, crude oil, and FII/DII data.
4. Provide a global & domestic news summary (max 150 words total) as bullet points."""
news_json_spec = """"news": [
{
"rank": 1,
"symbol": "SYMBOL_NAME",
"headline": "60–80 words. State clearly: (1) what happened, (2) why it matters, (3) what it means for Ram's position.",
"sentiment": "positive / negative / neutral",
"impact": "Critical / High / Medium / Low"
}
],"""
else:
news_instructions = """1. SKIP generating individual stock catalyst news stories for fast performance. Output "news": [] in the JSON response.
2. Search for today's Nifty, Sensex, crude oil price, and FII/DII data.
3. Provide a global & domestic news summary (max 150 words total) explaining today's key news and how it impacts Ram's portfolio."""
news_json_spec = """"news": [],"""
else:
news_json_spec = """"news": [],"""
return f"""You are PortIQ (Portfolio Intelligence), an institutional-grade risk & allocation advisor for Ram.
Ram is an Indian equity SIP investor who adds 1-2 shares daily with a multi-year horizon.
Today's Date: {today_date}
=== PORTFOLIO SNAPSHOT & RATIOS ===
{portfolio_text}
=== ALLOCATION LIMITS & STRATEGY CONTEXT ===
{strategy_context}
=== ADVISORY INSTRUCTIONS ===
{news_instructions}
---
### 1. HARD CAPITAL ALLOCATION GATES & FALLING KNIFE RISK FILTERS (MANDATORY CHECKS)
Before recommending any stock for "BUY" or "top_picks", evaluate these filters:
1. ALLOCATION CAP GATE:
- If a stock is flagged [MAX_WEIGHT_REACHED] (>= 7% of portfolio), you MUST assign "HOLD". Do not recommend adding more capital to an already oversized position.
2. SECTOR DIVERSIFICATION GATE & UNIFIED PHARMA/HEALTHCARE CAP:
- If a sector is flagged [SECTOR_CAP_EXCEEDED] (>= 18% of portfolio, e.g., IT Services or unified Pharma & Healthcare), you CANNOT recommend BUY for any stock in that sector.
- All healthcare, pharmaceutical, and hospital positions (CIPLA, DRREDDY, NATCOPHARM, ZYDUSLIFE, BIOCON, KMCSHIL) map to a single unified "Pharma & Healthcare" sector. When this sector reaches or exceeds the 18% cap (currently ~19.7%), pause all new accumulation across all pharma/healthcare stocks (assign "HOLD" to NATCOPHARM, etc.) and actively rotate capital into under-allocated sectors like Large-Cap Banking (e.g., HDFCBANK).
3. CONGLOMERATE AGGREGATE CAP GATE:
- If a conglomerate is flagged [CONGLOMERATE_CAP_EXCEEDED] (>= 22% of portfolio, e.g., Tata Group: TCS, TMPV, TMCV, TATACHEM, TATASTEEL, TATAPOWER, TITAN), you CANNOT recommend BUY for any stock in that conglomerate. Assign "HOLD" or "AVOID".
4. DEMERGER & ACCOUNTING ANOMALY GATE:
- If a stock is flagged [DEMERGER_ADJUSTED_COST_SUSPECT] (e.g., ITC with ITCHOTELS, TMPV with TMCV), the nominal price dip from average cost is an accounting artifact from a corporate spin-off. DO NOT treat this as an organic market discount. Assign "HOLD".
5. REGULATORY MOAT THREAT FILTER:
- If a stock is flagged [REGULATORY_MOAT_THREAT] or web search/filings reveal active regulatory disruption directly threatening market share or pricing power (e.g., CERC Market Coupling for IEX, government price caps, or license revocations):
- Immediately DISQUALIFY the stock from "top_picks" and assign "WATCH" or "AVOID". Never recommend BUY while structural regulatory erosion is underway.
6. CYCLICAL COMMODITY TROUGH FILTER:
- For commodity chemicals (e.g., Soda Ash like TATACHEM, Petrochemicals) or cyclical metals, consecutive quarters of YoY EBITDA/operating margin contraction caused by global oversupply must be treated as a CYCLICAL COMMODITY TROUGH, not a tactical dip.
- Disqualify from "top_picks" and "BUY" until realization growth and margins stabilize. Assign "WATCH" or "AVOID".
7. QUARTERLY EARNINGS & MARGIN DETERIORATION GATE:
- When evaluating any candidate stock with a discount > 15% (e.g., ARE&M): if the latest quarterly results show a YoY net profit decline > 25% or EBITDA margin compression > 150 bps, classify the dip as EARNINGS-DRIVEN MARGIN PRESSURE.
- Automatically DISQUALIFY the stock from "top_picks" and downgrade signal to "WATCH". Never treat structural margin erosion or profit collapse as a tactical dip.
8. MINIMUM BUY SCORE THRESHOLD (>= 25 POINTS):
- Enforce a strict minimum score threshold: a stock must achieve an institutional composite score >= 25 points to qualify for a "BUY" signal.
- Any stock scoring under 25 points (such as IRFC at 0pt or MUTHOOTFIN at 2pt) must strictly default to "HOLD" or "WATCH". Never assign "BUY" to any stock scoring < 25 points.
9. REBALANCED SCORING ENGINE (20% DIP / 50% QUALITY / 30% VALUATION):
- Price Dip %: Reduced from 50% to 20% weight (max 20 pts).
- Fundamental Quality: 50% weight (max 50 pts: ROE > 15%, low Debt/Equity, and steady quarterly operating margins).
- Valuation Safety: 30% weight (max 30 pts: P/E relative to 5-year median and distance from 52-week low).
- Quality compounders (e.g. HDFCBANK) MUST rank higher than high-drawdown cyclicals (e.g. ARE&M).
10. BFSI / LENDING SUB-SECTOR CONCENTRATION & MAXIMUM 1 FINANCIAL BUY:
- Group private banks, PSU lenders, and NBFCs (HDFCBANK, IDFCFIRSTB, INDUSINDBK, KTKBANK, MANAPPURAM, MUTHOOTFIN, SOUTHBANK, IRFC) under an umbrella "Financials & Lending" category.
- Cap aggregate Financials exposure at 20% of total portfolio value.
- RESTRICT DAILY BUY RECOMMENDATIONS TO A MAXIMUM OF ONE FINANCIAL STOCK PER SESSION to prevent correlated credit risk. If HDFCBANK is selected as the daily financial pick, do not recommend any other financial/lending stock (assign HOLD or WATCH to MUTHOOTFIN, IRFC, etc.).
11. CAPITAL ROTATION INTO CLEAN COMPOUNDERS:
- Prioritize high-quality, under-allocated fundamental compounders at attractive entries (specifically Large-Cap Banking like HDFCBANK) that clear all allocation gates, over over-allocated sectors (IT, Pharma & Healthcare) or earnings-pressured laggards. Never recommend chronic relative underperformers (e.g., WIPRO).
---
### 2. SEARCH BUDGET & LATENCY GUARD (MAX 3 SEARCHES TOTAL)
You are strictly limited to at most 3 Google Searches:
1. Macro Query (1 Search):
Query: "Nifty 50 Sensex market trend FII DII institutional activity today"
2. Candidate Catalyst Verification (Max 2 Searches):
Search ONLY for candidate stocks cleared by the Allocation Gates that show genuine tactical entry:
Query: "[SYMBOL] share price latest news quarterly earnings why moving"
DO NOT search for balance sheet ratios (use provided numbers).
DO NOT search for stocks in profit, over-allocated, or in saturated sectors.
---
### 3. OUTPUT SPECIFICATION (STRICT JSON ONLY)
Respond strictly in valid JSON matching this exact schema:
{{
"mood": {{
"market": "Bullish / Bearish / Cautious / Neutral",
"nifty_call": "gap up / flat / gap down",
"key_driver": "Clear concise macro driver (max 8 words)",
"tcr_mood": "Chai sip day / Active day / Wait and watch"
}},
"news_summary": [
"Macro or sector development and its direct portfolio impact."
],
"portfolio": [
{{
"symbol": "SYMBOL_NAME",
"signal": "BUY / HOLD / AVOID / WATCH",
"signal_reason": "One concise sentence focusing on valuation, concentration limit, or earnings posture."
}}
],
"top_picks": [
{{
"rank": 1,
"symbol": "SYMBOL_NAME",
"action": "Add 1 qty",
"reason": "Clear 2-sentence thesis highlighting moat, risk-reward, and diversification fit.",
"why_now": "Tactical trigger for today's deployment.",
"fundamental_verdict": "Strong / Moderate / Weak",
"risk": "The primary operational, competitive, or valuation risk."
}}
],
"avoid_today": [
{{
"symbol": "SYMBOL_NAME",
"reason": "Specific structural risk, sector saturation, or allocation cap reached."
}}
],
"market_summary": [
{{
"label": "Market Event",
"value": "Impact summary"
}}
],
{news_json_spec}
"dividends": [
{{
"symbol": "SYMBOL_NAME",
"amount": "₹X.XX per share",
"record_date": "YYYY-MM-DD or Upcoming"
}}
]
}}"""
def call_gemini(prompt, api_key=None):
"""
Calls the Gemini API using the modern google-genai SDK.
Enforces deterministic sampling (temperature=0.1) and handles
JSON configuration and search tools seamlessly.
Includes a single retry after 3 seconds on failure.
"""
active_key = api_key or GEMINI_API_KEY
if not active_key or active_key == "your_gemini_api_key_here":
raise ValueError("Valid GEMINI_API_KEY not found in .env file or Settings.")
from google import genai
from google.genai import types
client = genai.Client(api_key=active_key)
# Attempt response_mime_type="application/json" with temperature=0.1
try:
config = types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())],
response_mime_type="application/json",
temperature=0.1
)
except Exception:
config = types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())],
temperature=0.1
)
last_exception = None
for attempt in range(2):
try:
response = client.models.generate_content(
model='gemini-2.5-flash',
contents=prompt,
config=config
)
return response.text
except Exception as e:
# If Google API raises 400 because tool use with response_mime_type is unsupported,
# fallback immediately to config without response_mime_type at temperature=0.1
err_str = str(e).lower()
if "response mime type" in err_str or "unsupported" in err_str:
try:
fallback_config = types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())],
temperature=0.1
)
response = client.models.generate_content(
model='gemini-2.5-flash',
contents=prompt,
config=fallback_config
)
return response.text
except Exception as fb_err:
e = fb_err
last_exception = e
if attempt == 0:
print(f"API Call failed on first attempt: {e}. Retrying in 3 seconds...")
time.sleep(3)
else:
print(f"API Call failed on second attempt: {e}")
if last_exception:
raise last_exception
return None
def parse_response(raw_text):
"""
Cleans up the raw JSON string returned by the AI and parses it into a Python dict.
Includes regex extraction fallback to strip any surrounding markdown or commentary.
"""
if not raw_text:
return None
text = raw_text.strip()
# Strip markdown code blocks if the AI included them despite instructions
if text.startswith("```json"):
text = text[7:]
elif text.startswith("```"):
text = text[3:]
if text.endswith("```"):
text = text[:-3]
text = text.strip()
try:
data = json.loads(text)
return data
except json.JSONDecodeError as e:
import re
match = re.search(r'(\{[\s\S]*\})', text)
if match:
try:
return json.loads(match.group(1))
except Exception:
pass
print(f"Failed to parse JSON response: {e}")
print(f"Raw text was:\n{text}")
return None
def enrich_with_signal_prices(data, portfolio_df):
"""
Enriches the daily report data dictionary with _signal_prices by mapping
each signal in data["portfolio"] to the stock's LTP and quantity,
along with the Nifty 50 level from the market summary.
Applies post-generation risk guards and scoring validation.
"""
if not data or portfolio_df is None or portfolio_df.empty:
return data
try:
from modules.strategies import apply_post_generation_rules
data = apply_post_generation_rules(data, portfolio_df)
except Exception as rule_err:
print(f"[api_caller] apply_post_generation_rules warning: {rule_err}")
import re
# 1. Parse Nifty 50 on the day
nifty_on_day = None
market_summary = data.get("market_summary", [])
for item in market_summary:
label = item.get("label", "").lower()
if "nifty 50" in label or "nifty50" in label:
raw = item.get("value", "").replace(",", "")
match = re.search(r"[\d]+\.?\d*", raw)
if match:
try:
nifty_on_day = float(match.group())
except ValueError:
pass
break
# 2. Build maps for LTP and Qty
ltp_map = {}
qty_map = {}
for _, row in portfolio_df.iterrows():
sym = row.get("symbol")
if sym:
ltp_map[sym] = float(row.get("ltp") or 0)
qty_map[sym] = float(row.get("qty") or 0)
# 3. Build signal prices dict
signal_prices = {}
portfolio_signals = data.get("portfolio", [])
for entry in portfolio_signals:
sym = entry.get("symbol")
sig = entry.get("signal", "")
if sym and sig in ["BUY", "AVOID", "HOLD", "WATCH"] and sym in ltp_map and ltp_map[sym] > 0:
signal_prices[sym] = {
"signal": sig,
"price_on_day": ltp_map[sym],
"qty": qty_map.get(sym, 1.0),
"nifty_on_day": nifty_on_day
}
data["_signal_prices"] = signal_prices
return data
try:
import streamlit as st
cache_decorator = st.cache_data(ttl=1800)
except ImportError:
from functools import lru_cache
cache_decorator = lru_cache(maxsize=16)
@cache_decorator
def run_analysis(portfolio_text, strategy_context="No specific strategy context provided.", api_key=None, include_news=False):
"""
Orchestrates the analysis flow:
Builds the prompt, calls Gemini, and parses the response.
Returns (data_dict, error_message) tuple. error_message is None on success.
"""
try:
today_date = datetime.now().strftime("%Y-%m-%d")
prompt = build_tcr_prompt(portfolio_text, today_date, strategy_context, include_news=include_news)
raw_response = call_gemini(prompt, api_key=api_key)
if not raw_response:
return None, "Failed to get a valid response from the Gemini API."
parsed_data = parse_response(raw_response)
if not parsed_data:
return None, "Failed to parse the JSON response from Gemini."
return parsed_data, None
except Exception as e:
err_msg = str(e)
if "429" in err_msg or "quota" in err_msg.lower():
return None, "Gemini API rate limit or daily quota exceeded (429). If on the Free Tier, you are limited to 15 Requests Per Minute and 1500 Requests Per Day. Please wait 1 minute and try again."
return None, f"Analysis failed: {err_msg}"
def build_news_prompt(portfolio_text, today_date):
"""Builds a focused prompt for retrieving stock news and catalysts."""
return f"""
You are PortIQ (Portfolio Intelligence), a personal Indian stock portfolio advisor for Ram.
Today's date: {today_date}
Portfolio:
{portfolio_text}
Instructions:
1. Search for real-time news for the stocks in this portfolio using Google Search. To ensure a high-signal report, prioritize and retrieve news for the top 10-12 stocks with the most significant recent news, corporate announcements, earnings reports, or major price action.
2. For each selected stock, find the most recent and relevant news. Each headline must be between 60–80 words — complete and informative. Include: (a) what exactly happened, (b) why it matters for this stock, and (c) its direct impact on Ram's position. Do NOT write vague one-liners.
3. Assign each news item a global rank (1 = most important across entire portfolio) based on urgency and portfolio impact.
4. Assign an impact level: "Critical" (market-moving, act-now), "High" (significant, watch closely), "Medium" (notable but not urgent), "Low" (minor or long-term).
Respond ONLY in valid JSON with this exact structure (no markdown, no extra text):
{{
"news": [
{{
"rank": 1,
"symbol": "X",
"headline": "60–80 words. State clearly: (1) what happened — the actual event or development, (2) why it matters for this specific stock — fundamental, regulatory, or macro reason, (3) what it means for Ram's position — should he be concerned, watch, or is this a positive catalyst? Be specific, not vague.",
"sentiment": "positive/negative/neutral",
"impact": "Critical/High/Medium/Low"
}}
]
}}
"""
def run_news_analysis(portfolio_text, api_key=None, enable_finbert=True):
"""
On-demand catalyst news analysis:
Calls Gemini Search grounding to fetch portfolio news stories, then scores sentiment via FinBERT.
Returns (news_list, error_message).
"""
try:
today_date = datetime.now().strftime("%Y-%m-%d")
prompt = build_news_prompt(portfolio_text, today_date)
raw_response = call_gemini(prompt, api_key=api_key)
if not raw_response:
return None, "Failed to fetch catalyst news from Gemini API."
parsed_data = parse_response(raw_response)
if not parsed_data or "news" not in parsed_data:
return None, "Failed to parse news JSON response from Gemini."
news_list = parsed_data.get("news", [])
# Optional FinBERT sentiment scoring
if enable_finbert and news_list:
try:
from modules.sentiment import score_portfolio_news, load_sentiment_model
load_sentiment_model()
news_list = score_portfolio_news(news_list)
except Exception as fb_err:
print(f"[api] FinBERT news scoring failed: {fb_err}")
return news_list, None
except Exception as e:
err_msg = str(e)
if "429" in err_msg or "quota" in err_msg.lower():
return None, "Gemini API rate limit or daily quota exceeded (429). Please wait 1 minute and try again."
return None, f"News fetch failed: {err_msg}"
def run_chat_assistant(query, chat_history, active_date, active_report_data, active_portfolio_df, api_key=None):
"""
Runs the chat assistant to answer user questions about the dashboard data.
"""
try:
portfolio_text = ""
if active_portfolio_df is not None and not active_portfolio_df.empty:
portfolio_text = active_portfolio_df.to_string(index=False)
report_text = ""
if active_report_data:
report_copy = active_report_data.copy()
report_copy.pop("_portfolio_snapshot", None)
report_text = json.dumps(report_copy, indent=2)
history_text = ""
for msg in chat_history:
role = "User" if msg["role"] == "user" else "Assistant (PortIQ AI)"
history_text += f"{role}: {msg['content']}\n"
prompt = f"""
You are PortIQ (Portfolio Intelligence), Ram's personal Indian stock portfolio AI advisor.
Ram is asking you questions about the stock market dashboard and briefing showing for the date: {active_date}.
Here is the current dashboard data showing on Ram's screen for {active_date}:
--- Portfolio Snapshot ---
{portfolio_text}
--- Briefing Analysis (JSON) ---
{report_text}
--- Chat History ---
{history_text}
Ram's New Question:
{query}
Instructions:
1. Answer Ram's question clearly, concisely, and with high financial intelligence.
2. Reference the specific data shown on the dashboard (e.g., signals, news, top picks, metrics) to explain your reasoning.
3. If Ram asks about a stock suggestion (e.g. why buy, why avoid, or concerns about metrics like PE ratio), explain the context. If the dashboard suggested buying a stock, explain the reasoning from the "top_picks" or "portfolio" signal reasons, but also think critically about Ram's concerns (like a high PE ratio). Acknowledge their concern and provide a balanced view (e.g., high PE can indicate growth expectation, or high quality, or could indeed be a risk for short-term).
4. Keep the tone helpful, professional, yet conversational (like a friendly but sharp investment buddy).
5. Do NOT output JSON. Output regular formatting with paragraphs, bullet points, or simple markdown. Avoid verbose essays; keep it readable.
6. If the question requires current stock prices, PE ratios, or latest news not present in the dashboard, use your Google Search tool to fetch it.
"""
raw_response = call_gemini(prompt, api_key=api_key)
if not raw_response:
return "Failed to get a valid response from the Gemini API."
return raw_response
except Exception as e:
return f"Chat assistant encountered an error: {e}"
def build_recommendations_prompt(portfolio_symbols: list[str], today_date: str) -> str:
excluded_str = ", ".join(portfolio_symbols) if portfolio_symbols else "None"
return f"""
You are PortIQ (Portfolio Intelligence), an expert Indian stock market analyst and portfolio advisor.
Today's date: {today_date}
The user is looking for new investment opportunities that are NOT in their current portfolio.
Here are the stock symbols currently in the user's portfolio: {excluded_str}
Your task is to recommend the top 5 high-quality stocks listed on the NSE/BSE that are NOT in the list above.
These recommendations must strictly follow the fundamental valuation strategy.
Instructions:
1. Search the web for today's top Indian stock market ideas, sector performance, and potential bargains.
2. Filter out any stock that is in the excluded list: {excluded_str}.
3. Apply the following VALUATION STRATEGY rules to select the top 5 recommendations:
- VALUATION: The stock should be cheap or reasonably valued. Stock P/E should be close to or below its industry benchmark (e.g., Banking ~12-15 | IT ~25-30 | Pharma ~25-35 | FMCG ~45-55 | Auto ~20-25 | Infra ~15-20). The Price-to-Book (P/B) ratio should be attractive.
- PROFITABILITY: The company must be highly profitable. ROE > 15% and ROCE > 15% (or ROA > 1% for banks). Operating Profit Margin (OPM) must be stable or improving.
- FINANCIAL SAFETY: Low leverage. Debt-to-Equity (D/E) should be < 0.5 (or < 1.0, and up to 2.0 for infrastructure). Promoter holding should ideally be > 50% and stable.
- MOMENTUM: Technical RSI should be in a healthy accumulation zone (< 60 preferred, not overbought).
- RECENT NEWS: Ensure there are no major governance, regulatory, or operational red flags in the news today.
4. Respond ONLY in valid JSON with this exact structure (no markdown, no extra text, strictly valid JSON):
{{
"recommendations": [
{{
"rank": 1,
"symbol": "SYMBOL",
"company_name": "Full Company Name",
"sector": "Sector/Industry",
"price": 1234.50,
"pe": 22.4,
"pb": 4.2,
"roe": 19.5,
"debt_to_equity": 0.1,
"reason": "1-2 sentences detailing the core fundamental strength and why it aligns with the valuation strategy.",
"why_now": "1-2 sentences on the near-term catalyst or reason today is a good entry point.",
"risks": "One key risk to monitor for this company."
}}
]
}}
"""
def run_recommendations_analysis(portfolio_symbols: list[str], api_key: str = None):
"""
Orchestrates search-grounded recommendation retrieval.
"""
try:
today_date = datetime.now().strftime("%Y-%m-%d")
prompt = build_recommendations_prompt(portfolio_symbols, today_date)
raw_response = call_gemini(prompt, api_key=api_key)
if not raw_response:
return None, "Failed to get a response from the Gemini API."
parsed_data = parse_response(raw_response)
if not parsed_data:
return None, "Failed to parse the recommendation JSON."
return parsed_data, None
except Exception as e:
return None, f"Recommendations fetch failed with error: {e}"