Spaces:
Running
Running
fix: mentor returns real roast from numeric summary when LLM output is empty/malformed
Browse files- agents.py +20 -17
- mentor.py +113 -22
- tests/e2e_test.py +19 -0
agents.py
CHANGED
|
@@ -63,26 +63,29 @@ def generate(prompt: str, system: str = "", max_tokens: int = 256, temperature:
|
|
| 63 |
messages.append({"role": "system", "content": system})
|
| 64 |
messages.append({"role": "user", "content": prompt})
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
return ""
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
|
| 85 |
-
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
def mock_generate(prompt: str, system: str = "") -> str:
|
|
|
|
| 63 |
messages.append({"role": "system", "content": system})
|
| 64 |
messages.append({"role": "user", "content": prompt})
|
| 65 |
|
| 66 |
+
# Try once, then retry with a lower temperature if empty (model can
|
| 67 |
+
# produce empty/garbage on the first try under high temperature).
|
| 68 |
+
for attempt, (mt, temp) in enumerate([(max_tokens, temperature), (max_tokens, 0.2)]):
|
| 69 |
+
try:
|
| 70 |
+
response = llm.create_chat_completion(
|
| 71 |
+
messages=messages,
|
| 72 |
+
max_tokens=mt,
|
| 73 |
+
temperature=temp,
|
| 74 |
+
)
|
| 75 |
+
except Exception as e:
|
| 76 |
+
print(f"Warning: LLM call failed (attempt {attempt}): {e}.")
|
| 77 |
+
continue
|
| 78 |
|
| 79 |
+
try:
|
| 80 |
+
content = response["choices"][0]["message"]["content"]
|
| 81 |
+
except (KeyError, IndexError, TypeError):
|
| 82 |
+
continue
|
|
|
|
| 83 |
|
| 84 |
+
if isinstance(content, str) and content.strip():
|
| 85 |
+
return clean_text(content)
|
| 86 |
|
| 87 |
+
print("Warning: LLM returned empty content after retries.")
|
| 88 |
+
return ""
|
| 89 |
|
| 90 |
|
| 91 |
def mock_generate(prompt: str, system: str = "") -> str:
|
mentor.py
CHANGED
|
@@ -2,35 +2,126 @@
|
|
| 2 |
|
| 3 |
import json
|
| 4 |
import re
|
|
|
|
| 5 |
|
| 6 |
from agents import generate
|
| 7 |
|
| 8 |
|
| 9 |
-
def
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
try:
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
def generate_review(summary: dict) -> dict:
|
| 27 |
-
system =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
prompt = (
|
| 29 |
-
f"Starting
|
| 30 |
-
f"Ending
|
| 31 |
-
f"
|
| 32 |
-
f"
|
| 33 |
-
f"
|
| 34 |
)
|
| 35 |
-
response = generate(prompt, system=system, max_tokens=
|
| 36 |
-
return parse_mentor_response(response)
|
|
|
|
| 2 |
|
| 3 |
import json
|
| 4 |
import re
|
| 5 |
+
from typing import Dict
|
| 6 |
|
| 7 |
from agents import generate
|
| 8 |
|
| 9 |
|
| 10 |
+
def _deterministic_review(summary: Dict) -> Dict:
|
| 11 |
+
"""Build a real, useful mentor review from the numeric summary alone.
|
| 12 |
+
|
| 13 |
+
Used when the LLM is unavailable or returns unparseable output, so the
|
| 14 |
+
player always gets an actual roast grounded in their numbers (never a
|
| 15 |
+
raw parse error).
|
| 16 |
+
"""
|
| 17 |
+
starting = float(summary.get("starting_value", 1_000_000))
|
| 18 |
+
ending = float(summary.get("ending_value", starting))
|
| 19 |
+
sharpe = float(summary.get("sharpe_ratio", 0.0))
|
| 20 |
+
allocations = summary.get("allocations") or {}
|
| 21 |
+
total_alloc = sum(float(v) for v in allocations.values())
|
| 22 |
+
|
| 23 |
+
# Pick a deterministic roast based on performance band
|
| 24 |
+
pct_change = ((ending - starting) / starting * 100.0) if starting else 0.0
|
| 25 |
+
if pct_change >= 100:
|
| 26 |
+
roast = f"You doubled the book. Buffett is taking notes."
|
| 27 |
+
elif pct_change >= 25:
|
| 28 |
+
roast = f"Compounding works. Even your broker is surprised."
|
| 29 |
+
elif pct_change >= 0:
|
| 30 |
+
roast = f"You survived. The market didn't kill you. Yet."
|
| 31 |
+
elif pct_change >= -25:
|
| 32 |
+
roast = f"Pain is tuition. You paid for a semester."
|
| 33 |
+
else:
|
| 34 |
+
roast = f"That wasn't investing. That was a donation."
|
| 35 |
+
|
| 36 |
+
# Find the dominant allocation and call it out
|
| 37 |
+
if allocations:
|
| 38 |
+
biggest = max(allocations.items(), key=lambda kv: kv[1])
|
| 39 |
+
asset_name = str(biggest[0]).replace("_", " ")
|
| 40 |
+
share_pct = float(biggest[1]) * 100
|
| 41 |
+
if share_pct >= 70 and asset_name not in ("cash", "fd"):
|
| 42 |
+
lesson = f"{share_pct:.0f}% in {asset_name} is conviction, not a plan."
|
| 43 |
+
suggestion = f"Cap {asset_name} at 40%. Add bonds or gold."
|
| 44 |
+
elif total_alloc < 0.3:
|
| 45 |
+
lesson = "Idle cash lost to inflation this year."
|
| 46 |
+
suggestion = "Move 30% of cash into FD or gov bonds."
|
| 47 |
+
else:
|
| 48 |
+
lesson = "Sharpe ratio measures return per unit of pain."
|
| 49 |
+
suggestion = "Trim the weakest performer and rebalance."
|
| 50 |
+
else:
|
| 51 |
+
lesson = "Sharpe ratio measures return per unit of pain."
|
| 52 |
+
suggestion = "Build a core allocation: 50% Nifty, 20% bonds, 10% gold."
|
| 53 |
+
|
| 54 |
+
if sharpe >= 1.0:
|
| 55 |
+
suggestion = "Sharpe > 1: lock in gains, don't get heroic."
|
| 56 |
+
elif sharpe <= 0:
|
| 57 |
+
suggestion = "Negative Sharpe: cut losers, raise cash."
|
| 58 |
+
|
| 59 |
+
return {
|
| 60 |
+
"roast": roast[:80],
|
| 61 |
+
"sharpe_ratio": round(sharpe, 2),
|
| 62 |
+
"lesson": lesson[:140],
|
| 63 |
+
"suggestion": suggestion[:80],
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def parse_mentor_response(response: str, summary: Dict) -> dict:
|
| 68 |
+
"""Parse the LLM's structured review. Falls back to a numeric roast
|
| 69 |
+
derived from the summary if the LLM output is empty or malformed,
|
| 70 |
+
so the player never sees a raw 'Parse error' message."""
|
| 71 |
+
if not response or not response.strip():
|
| 72 |
+
return _deterministic_review(summary)
|
| 73 |
+
|
| 74 |
+
text = response.strip()
|
| 75 |
+
roast = sharpe_s = lesson = suggestion = None
|
| 76 |
+
try:
|
| 77 |
+
m = re.search(r"roast:\s*(.+)", text)
|
| 78 |
+
if m:
|
| 79 |
+
roast = m.group(1).strip()
|
| 80 |
+
except Exception:
|
| 81 |
+
pass
|
| 82 |
+
try:
|
| 83 |
+
m = re.search(r"sharpe_ratio:\s*([-\d.]+)", text)
|
| 84 |
+
if m:
|
| 85 |
+
sharpe_s = float(m.group(1))
|
| 86 |
+
except Exception:
|
| 87 |
+
pass
|
| 88 |
try:
|
| 89 |
+
m = re.search(r"lesson:\s*(.+)", text)
|
| 90 |
+
if m:
|
| 91 |
+
lesson = m.group(1).strip()
|
| 92 |
+
except Exception:
|
| 93 |
+
pass
|
| 94 |
+
try:
|
| 95 |
+
m = re.search(r"suggestion:\s*(.+)", text)
|
| 96 |
+
if m:
|
| 97 |
+
suggestion = m.group(1).strip()
|
| 98 |
+
except Exception:
|
| 99 |
+
pass
|
| 100 |
+
|
| 101 |
+
fallback = _deterministic_review(summary)
|
| 102 |
+
return {
|
| 103 |
+
"roast": (roast or fallback["roast"])[:80],
|
| 104 |
+
"sharpe_ratio": sharpe_s if sharpe_s is not None else fallback["sharpe_ratio"],
|
| 105 |
+
"lesson": (lesson or fallback["lesson"])[:140],
|
| 106 |
+
"suggestion": (suggestion or fallback["suggestion"])[:80],
|
| 107 |
+
}
|
| 108 |
|
| 109 |
|
| 110 |
def generate_review(summary: dict) -> dict:
|
| 111 |
+
system = (
|
| 112 |
+
"You are a sarcastic but caring Indian finance professor in a video game. "
|
| 113 |
+
"Output a year-end review in EXACT format (one line each):\n"
|
| 114 |
+
"roast: <witty roast, under 60 chars>\n"
|
| 115 |
+
"sharpe_ratio: <number, e.g. 0.85>\n"
|
| 116 |
+
"lesson: <explain Sharpe ratio simply, under 100 chars>\n"
|
| 117 |
+
"suggestion: <one concrete tip, under 60 chars>"
|
| 118 |
+
)
|
| 119 |
prompt = (
|
| 120 |
+
f"Starting ₹{summary['starting_value']:,.0f}. "
|
| 121 |
+
f"Ending ₹{summary['ending_value']:,.0f}. "
|
| 122 |
+
f"Drawdown {summary['max_drawdown']*100:.0f}%. "
|
| 123 |
+
f"Sharpe {summary['sharpe_ratio']}. "
|
| 124 |
+
f"Top alloc: {max(summary['allocations'].items(), key=lambda kv: kv[1]) if summary['allocations'] else 'cash'}."
|
| 125 |
)
|
| 126 |
+
response = generate(prompt, system=system, max_tokens=200, temperature=0.5)
|
| 127 |
+
return parse_mentor_response(response, summary)
|
tests/e2e_test.py
CHANGED
|
@@ -165,6 +165,25 @@ check("mentor has review", "review" in data)
|
|
| 165 |
check("mentor review has roast", "roast" in data["review"])
|
| 166 |
check("mentor review has lesson", "lesson" in data["review"])
|
| 167 |
check("mentor review has suggestion", "suggestion" in data["review"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
print("\n=== Reset ===")
|
| 170 |
r = client.post("/api/reset")
|
|
|
|
| 165 |
check("mentor review has roast", "roast" in data["review"])
|
| 166 |
check("mentor review has lesson", "lesson" in data["review"])
|
| 167 |
check("mentor review has suggestion", "suggestion" in data["review"])
|
| 168 |
+
# No raw parse error leaks
|
| 169 |
+
rev = data["review"]
|
| 170 |
+
check("roast is not raw parse error", rev["roast"] != "Could not parse review.")
|
| 171 |
+
check("no 'Parse error' in lesson", "Parse error" not in rev.get("lesson", ""))
|
| 172 |
+
|
| 173 |
+
print("\n=== Mentor fallback (forced empty LLM) returns real roast ===")
|
| 174 |
+
_orig_gen = app_module.mentor.generate
|
| 175 |
+
def _empty_llm(summary):
|
| 176 |
+
return app_module.mentor.parse_mentor_response("", summary)
|
| 177 |
+
app_module.mentor.generate_review = _empty_llm
|
| 178 |
+
try:
|
| 179 |
+
r = client.get("/api/mentor")
|
| 180 |
+
check("mentor fallback 200", r.status_code == 200)
|
| 181 |
+
rev2 = r.json()["review"]
|
| 182 |
+
check("fallback roast is real (not parse error)", rev2["roast"] != "Could not parse review.")
|
| 183 |
+
check("fallback roast non-empty", len(rev2["roast"]) > 0)
|
| 184 |
+
check("fallback suggestion non-empty", len(rev2["suggestion"]) > 0)
|
| 185 |
+
finally:
|
| 186 |
+
app_module.mentor.generate_review = _orig_gen
|
| 187 |
|
| 188 |
print("\n=== Reset ===")
|
| 189 |
r = client.post("/api/reset")
|