Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,46 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from fastapi import FastAPI
|
| 3 |
from fastapi.responses import HTMLResponse
|
| 4 |
-
from pydantic import BaseModel
|
| 5 |
-
import
|
| 6 |
-
import re
|
| 7 |
import math
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
app = FastAPI()
|
| 10 |
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
#
|
| 14 |
-
#
|
|
|
|
| 15 |
class ChatMessage(BaseModel):
|
| 16 |
role: str
|
| 17 |
text: str
|
|
@@ -19,7 +48,7 @@ class ChatMessage(BaseModel):
|
|
| 19 |
|
| 20 |
class ChatRequest(BaseModel):
|
| 21 |
message: str
|
| 22 |
-
chat_history:
|
| 23 |
tone: float = 0.5
|
| 24 |
verbosity: float = 0.5
|
| 25 |
transparency: float = 0.5
|
|
@@ -27,349 +56,1101 @@ class ChatRequest(BaseModel):
|
|
| 27 |
|
| 28 |
class ChatResponse(BaseModel):
|
| 29 |
reply: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
# -----------------------------
|
| 33 |
-
# Simple homepage UI
|
| 34 |
-
# -----------------------------
|
| 35 |
-
@app.get("/", response_class=HTMLResponse)
|
| 36 |
-
def home():
|
| 37 |
-
return """
|
| 38 |
-
<html>
|
| 39 |
-
<head>
|
| 40 |
-
<title>Trading Game AI Test</title>
|
| 41 |
-
<style>
|
| 42 |
-
body {
|
| 43 |
-
font-family: Arial, sans-serif;
|
| 44 |
-
max-width: 900px;
|
| 45 |
-
margin: 40px auto;
|
| 46 |
-
padding: 20px;
|
| 47 |
-
}
|
| 48 |
-
textarea {
|
| 49 |
-
width: 100%;
|
| 50 |
-
font-size: 16px;
|
| 51 |
-
}
|
| 52 |
-
.slider-row {
|
| 53 |
-
margin: 12px 0;
|
| 54 |
-
}
|
| 55 |
-
.chat-box {
|
| 56 |
-
border: 1px solid #ccc;
|
| 57 |
-
padding: 12px;
|
| 58 |
-
min-height: 220px;
|
| 59 |
-
margin-top: 20px;
|
| 60 |
-
white-space: pre-wrap;
|
| 61 |
-
background: #f9f9f9;
|
| 62 |
-
}
|
| 63 |
-
button {
|
| 64 |
-
padding: 10px 16px;
|
| 65 |
-
font-size: 16px;
|
| 66 |
-
margin-right: 10px;
|
| 67 |
-
cursor: pointer;
|
| 68 |
-
}
|
| 69 |
-
</style>
|
| 70 |
-
</head>
|
| 71 |
-
<body>
|
| 72 |
-
<h2>Trading Game AI Tester</h2>
|
| 73 |
-
|
| 74 |
-
<label><strong>Message</strong></label><br>
|
| 75 |
-
<textarea id="msg" rows="5" placeholder="Type a test prompt here..."></textarea><br><br>
|
| 76 |
-
|
| 77 |
-
<div class="slider-row">
|
| 78 |
-
<label><strong>Tone:</strong> <span id="toneVal">0.5</span></label><br>
|
| 79 |
-
<input type="range" id="tone" min="0" max="1" step="0.01" value="0.5" oninput="toneVal.innerText=this.value">
|
| 80 |
-
</div>
|
| 81 |
-
|
| 82 |
-
<div class="slider-row">
|
| 83 |
-
<label><strong>Verbosity:</strong> <span id="verbosityVal">0.5</span></label><br>
|
| 84 |
-
<input type="range" id="verbosity" min="0" max="1" step="0.01" value="0.5" oninput="verbosityVal.innerText=this.value">
|
| 85 |
-
</div>
|
| 86 |
-
|
| 87 |
-
<div class="slider-row">
|
| 88 |
-
<label><strong>Transparency:</strong> <span id="transparencyVal">0.5</span></label><br>
|
| 89 |
-
<input type="range" id="transparency" min="0" max="1" step="0.01" value="0.5" oninput="transparencyVal.innerText=this.value">
|
| 90 |
-
</div>
|
| 91 |
-
|
| 92 |
-
<br>
|
| 93 |
-
<button onclick="sendMessage()">Send</button>
|
| 94 |
-
<button onclick="clearChat()">Clear</button>
|
| 95 |
-
|
| 96 |
-
<div id="chat" class="chat-box"></div>
|
| 97 |
-
|
| 98 |
-
<script>
|
| 99 |
-
let history = [];
|
| 100 |
-
|
| 101 |
-
async function sendMessage() {
|
| 102 |
-
const message = document.getElementById("msg").value.trim();
|
| 103 |
-
if (!message) return;
|
| 104 |
-
|
| 105 |
-
const tone = parseFloat(document.getElementById("tone").value);
|
| 106 |
-
const verbosity = parseFloat(document.getElementById("verbosity").value);
|
| 107 |
-
const transparency = parseFloat(document.getElementById("transparency").value);
|
| 108 |
-
const chatBox = document.getElementById("chat");
|
| 109 |
-
|
| 110 |
-
chatBox.innerText += "\\nUSER: " + message + "\\n";
|
| 111 |
-
chatBox.innerText += "AI: [waiting for response...]\\n";
|
| 112 |
-
document.getElementById("msg").value = "";
|
| 113 |
-
|
| 114 |
-
const payload = {
|
| 115 |
-
message: message,
|
| 116 |
-
chat_history: history,
|
| 117 |
-
tone: tone,
|
| 118 |
-
verbosity: verbosity,
|
| 119 |
-
transparency: transparency
|
| 120 |
-
};
|
| 121 |
-
|
| 122 |
-
try {
|
| 123 |
-
const res = await fetch("/chat", {
|
| 124 |
-
method: "POST",
|
| 125 |
-
headers: { "Content-Type": "application/json" },
|
| 126 |
-
body: JSON.stringify(payload)
|
| 127 |
-
});
|
| 128 |
-
|
| 129 |
-
const data = await res.json();
|
| 130 |
-
|
| 131 |
-
chatBox.innerText = chatBox.innerText.replace(
|
| 132 |
-
"AI: [waiting for response...]",
|
| 133 |
-
"AI: " + data.reply
|
| 134 |
-
);
|
| 135 |
-
|
| 136 |
-
history.push({ role: "user", text: message });
|
| 137 |
-
history.push({ role: "assistant", text: data.reply });
|
| 138 |
-
} catch (err) {
|
| 139 |
-
chatBox.innerText = chatBox.innerText.replace(
|
| 140 |
-
"AI: [waiting for response...]",
|
| 141 |
-
"AI: ERROR: request failed"
|
| 142 |
-
);
|
| 143 |
-
}
|
| 144 |
-
}
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
# -----------------------------
|
| 157 |
-
# Health/status route
|
| 158 |
-
# -----------------------------
|
| 159 |
-
@app.get("/status")
|
| 160 |
-
def status():
|
| 161 |
-
return {"status": "TradingGameAI running"}
|
| 162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
-
# -----------------------------
|
| 165 |
-
# Style helpers
|
| 166 |
-
# -----------------------------
|
| 167 |
-
def get_tone_prefix(tone: float) -> str:
|
| 168 |
if tone < 0.33:
|
| 169 |
-
|
| 170 |
elif tone < 0.66:
|
| 171 |
-
|
| 172 |
else:
|
| 173 |
-
|
| 174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
-
|
| 177 |
-
t = text.lower()
|
| 178 |
-
return "hint only" in t or "just a hint" in t or "give me a hint" in t
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
-
def format_number(value: float):
|
| 182 |
-
if isinstance(value, (int,)):
|
| 183 |
-
return value
|
| 184 |
-
if isinstance(value, float) and value.is_integer():
|
| 185 |
-
return int(value)
|
| 186 |
-
return round(value, 6)
|
| 187 |
|
|
|
|
|
|
|
| 188 |
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
t = text.lower().replace("×", "*").replace("x", "*").replace("÷", "/")
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
|
| 201 |
-
for pattern in patterns:
|
| 202 |
-
match = re.search(pattern, t)
|
| 203 |
-
if match:
|
| 204 |
-
a = float(match.group(1))
|
| 205 |
-
op = match.group(2)
|
| 206 |
-
b = float(match.group(3))
|
| 207 |
-
return a, op, b
|
| 208 |
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
| 210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
-
def solve_arithmetic(a: float, op: str, b: float):
|
| 213 |
-
if op == "+":
|
| 214 |
-
return a + b
|
| 215 |
-
if op == "-":
|
| 216 |
-
return a - b
|
| 217 |
-
if op == "*":
|
| 218 |
-
return a * b
|
| 219 |
-
if op == "/":
|
| 220 |
-
if b == 0:
|
| 221 |
-
return None
|
| 222 |
-
return a / b
|
| 223 |
return None
|
| 224 |
|
| 225 |
|
| 226 |
-
def
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
symbol = "÷"
|
| 244 |
-
|
| 245 |
-
hint_only = wants_hint_only(req.message)
|
| 246 |
-
|
| 247 |
-
if hint_only:
|
| 248 |
-
if op == "+":
|
| 249 |
-
hint_core = f"Try combining {a_fmt} and {b_fmt} step by step."
|
| 250 |
-
elif op == "-":
|
| 251 |
-
hint_core = f"Think about taking {b_fmt} away from {a_fmt}."
|
| 252 |
-
elif op == "*":
|
| 253 |
-
hint_core = f"Think of multiplication as repeated addition."
|
| 254 |
-
else:
|
| 255 |
-
hint_core = f"Think about how many times {b_fmt} fits into {a_fmt}."
|
| 256 |
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
else:
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
)
|
| 288 |
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
)
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
)
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
)
|
| 310 |
|
|
|
|
| 311 |
|
| 312 |
-
# -----------------------------
|
| 313 |
-
# Basic verbal fallback
|
| 314 |
-
# -----------------------------
|
| 315 |
-
def build_non_math_reply(req: ChatRequest):
|
| 316 |
-
intro = get_tone_prefix(req.tone)
|
| 317 |
-
text = req.message.strip()
|
| 318 |
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
return (
|
| 336 |
-
f"{
|
| 337 |
-
|
| 338 |
)
|
| 339 |
|
| 340 |
return (
|
| 341 |
-
f"{
|
| 342 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
)
|
| 344 |
|
| 345 |
|
| 346 |
-
#
|
| 347 |
-
#
|
| 348 |
-
#
|
| 349 |
-
@app.post("/chat", response_model=ChatResponse)
|
| 350 |
-
def chat(req: ChatRequest):
|
| 351 |
-
try:
|
| 352 |
-
parsed = parse_simple_arithmetic(req.message)
|
| 353 |
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
|
| 358 |
-
|
| 359 |
-
|
|
|
|
| 360 |
|
| 361 |
-
|
| 362 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
-
|
| 365 |
-
|
|
|
|
|
|
|
| 366 |
|
| 367 |
-
|
| 368 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 369 |
|
| 370 |
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
# GMAT Solver v2 + Math-Verify integration
|
| 3 |
+
# FastAPI backend for a Unity trading-game study AI
|
| 4 |
+
#
|
| 5 |
+
# Features:
|
| 6 |
+
# - Keeps the same /chat schema used by Unity:
|
| 7 |
+
# { message, chat_history, tone, verbosity, transparency }
|
| 8 |
+
# - Rule-based / symbolic GMAT-style quant solver
|
| 9 |
+
# - Strategy-first support for verbal questions
|
| 10 |
+
# - Transparency slider affects hint / guided / answer mode
|
| 11 |
+
# - Math-Verify integration for answer validation metadata
|
| 12 |
+
# - Simple browser test UI at "/"
|
| 13 |
+
|
| 14 |
from fastapi import FastAPI
|
| 15 |
from fastapi.responses import HTMLResponse
|
| 16 |
+
from pydantic import BaseModel, Field
|
| 17 |
+
from typing import List, Optional, Dict, Any, Tuple
|
|
|
|
| 18 |
import math
|
| 19 |
+
import statistics
|
| 20 |
+
import re
|
| 21 |
+
import ast
|
| 22 |
+
import operator as op
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
import sympy as sp
|
| 26 |
+
SYMPY_AVAILABLE = True
|
| 27 |
+
except Exception:
|
| 28 |
+
SYMPY_AVAILABLE = False
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
from math_verify import parse, verify
|
| 32 |
+
MATH_VERIFY_AVAILABLE = True
|
| 33 |
+
except Exception:
|
| 34 |
+
MATH_VERIFY_AVAILABLE = False
|
| 35 |
+
|
| 36 |
|
| 37 |
+
app = FastAPI(title="GMAT Solver v2")
|
| 38 |
|
| 39 |
|
| 40 |
+
# =========================================================
|
| 41 |
+
# Models
|
| 42 |
+
# =========================================================
|
| 43 |
+
|
| 44 |
class ChatMessage(BaseModel):
|
| 45 |
role: str
|
| 46 |
text: str
|
|
|
|
| 48 |
|
| 49 |
class ChatRequest(BaseModel):
|
| 50 |
message: str
|
| 51 |
+
chat_history: List[ChatMessage] = Field(default_factory=list)
|
| 52 |
tone: float = 0.5
|
| 53 |
verbosity: float = 0.5
|
| 54 |
transparency: float = 0.5
|
|
|
|
| 56 |
|
| 57 |
class ChatResponse(BaseModel):
|
| 58 |
reply: str
|
| 59 |
+
meta: Optional[Dict[str, Any]] = None
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class SolveResult(BaseModel):
|
| 63 |
+
solved: bool = False
|
| 64 |
+
answer_letter: Optional[str] = None
|
| 65 |
+
answer_value: Optional[str] = None
|
| 66 |
+
confidence: float = 0.0
|
| 67 |
+
method: str = ""
|
| 68 |
+
reasoning: List[str] = Field(default_factory=list)
|
| 69 |
+
caution: Optional[str] = None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# =========================================================
|
| 73 |
+
# Safe arithmetic evaluator
|
| 74 |
+
# =========================================================
|
| 75 |
+
|
| 76 |
+
_ALLOWED_OPERATORS = {
|
| 77 |
+
ast.Add: op.add,
|
| 78 |
+
ast.Sub: op.sub,
|
| 79 |
+
ast.Mult: op.mul,
|
| 80 |
+
ast.Div: op.truediv,
|
| 81 |
+
ast.Pow: op.pow,
|
| 82 |
+
ast.USub: op.neg,
|
| 83 |
+
ast.Mod: op.mod,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
_ALLOWED_FUNCS = {
|
| 87 |
+
"sqrt": math.sqrt,
|
| 88 |
+
"abs": abs,
|
| 89 |
+
"ceil": math.ceil,
|
| 90 |
+
"floor": math.floor,
|
| 91 |
+
"log10": math.log10,
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
_ALLOWED_CONSTS = {
|
| 95 |
+
"pi": math.pi,
|
| 96 |
+
"e": math.e,
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def safe_eval(expr: str) -> Optional[float]:
|
| 101 |
+
expr = expr.replace("^", "**")
|
| 102 |
+
|
| 103 |
+
def _eval(node):
|
| 104 |
+
if isinstance(node, ast.Constant):
|
| 105 |
+
if isinstance(node.value, (int, float)):
|
| 106 |
+
return node.value
|
| 107 |
+
raise ValueError("Invalid constant")
|
| 108 |
+
elif isinstance(node, ast.Num):
|
| 109 |
+
return node.n
|
| 110 |
+
elif isinstance(node, ast.BinOp):
|
| 111 |
+
if type(node.op) not in _ALLOWED_OPERATORS:
|
| 112 |
+
raise ValueError("Operator not allowed")
|
| 113 |
+
return _ALLOWED_OPERATORS[type(node.op)](_eval(node.left), _eval(node.right))
|
| 114 |
+
elif isinstance(node, ast.UnaryOp):
|
| 115 |
+
if type(node.op) not in _ALLOWED_OPERATORS:
|
| 116 |
+
raise ValueError("Unary operator not allowed")
|
| 117 |
+
return _ALLOWED_OPERATORS[type(node.op)](_eval(node.operand))
|
| 118 |
+
elif isinstance(node, ast.Call):
|
| 119 |
+
if not isinstance(node.func, ast.Name):
|
| 120 |
+
raise ValueError("Invalid call")
|
| 121 |
+
fname = node.func.id
|
| 122 |
+
if fname not in _ALLOWED_FUNCS:
|
| 123 |
+
raise ValueError("Function not allowed")
|
| 124 |
+
args = [_eval(a) for a in node.args]
|
| 125 |
+
return _ALLOWED_FUNCS[fname](*args)
|
| 126 |
+
elif isinstance(node, ast.Name):
|
| 127 |
+
if node.id in _ALLOWED_CONSTS:
|
| 128 |
+
return _ALLOWED_CONSTS[node.id]
|
| 129 |
+
raise ValueError("Name not allowed")
|
| 130 |
+
raise ValueError("Unsupported expression")
|
| 131 |
|
| 132 |
+
try:
|
| 133 |
+
tree = ast.parse(expr, mode="eval")
|
| 134 |
+
value = _eval(tree.body)
|
| 135 |
+
return float(value)
|
| 136 |
+
except Exception:
|
| 137 |
+
return None
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
+
# =========================================================
|
| 141 |
+
# Helpers
|
| 142 |
+
# =========================================================
|
| 143 |
+
|
| 144 |
+
def clamp(v: float, lo: float, hi: float) -> float:
|
| 145 |
+
return max(lo, min(hi, v))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def normalize_text(s: str) -> str:
|
| 149 |
+
s = s.replace("\r\n", "\n")
|
| 150 |
+
s = s.replace("—", "-").replace("–", "-")
|
| 151 |
+
s = re.sub(r"[ \t]+", " ", s)
|
| 152 |
+
return s.strip()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def lower_clean(s: str) -> str:
|
| 156 |
+
return normalize_text(s).lower()
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def format_number(x: float) -> str:
|
| 160 |
+
if abs(x - round(x)) < 1e-9:
|
| 161 |
+
return str(int(round(x)))
|
| 162 |
+
return f"{x:.6f}".rstrip("0").rstrip(".")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def format_fraction_or_decimal(x: float) -> str:
|
| 166 |
+
if x == 0:
|
| 167 |
+
return "0"
|
| 168 |
+
for d in range(2, 21):
|
| 169 |
+
n = x * d
|
| 170 |
+
if abs(n - round(n)) < 1e-9:
|
| 171 |
+
return f"{int(round(n))}/{d}"
|
| 172 |
+
return format_number(x)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def last_n_messages(history: List[ChatMessage], n: int = 8) -> str:
|
| 176 |
+
parts = []
|
| 177 |
+
for m in history[-n:]:
|
| 178 |
+
parts.append(f"{m.role.upper()}: {m.text}")
|
| 179 |
+
return "\n".join(parts)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def extract_options(text: str) -> List[Tuple[str, str]]:
|
| 183 |
+
pattern = re.compile(r'(?mi)^\s*(?:\(?([A-E])\)|([A-E])[.)]?)[ \t]+(.+?)\s*$')
|
| 184 |
+
found = []
|
| 185 |
+
for line in text.splitlines():
|
| 186 |
+
m = pattern.match(line.strip())
|
| 187 |
+
if m:
|
| 188 |
+
letter = m.group(1) or m.group(2)
|
| 189 |
+
value = m.group(3).strip()
|
| 190 |
+
found.append((letter.upper(), value))
|
| 191 |
+
return found
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def strip_options(text: str) -> str:
|
| 195 |
+
lines = text.splitlines()
|
| 196 |
+
kept = []
|
| 197 |
+
opt_pat = re.compile(r'(?mi)^\s*(?:\(?[A-E]\)|[A-E][.)]?)[ \t]+.+$')
|
| 198 |
+
for line in lines:
|
| 199 |
+
if not opt_pat.match(line.strip()):
|
| 200 |
+
kept.append(line)
|
| 201 |
+
return "\n".join(kept).strip()
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def contains_math_signal(text: str) -> bool:
|
| 205 |
+
signals = [
|
| 206 |
+
"+", "-", "*", "/", "%", "percent", "ratio", "average", "mean", "median",
|
| 207 |
+
"integer", "divisible", "probability", "permutation", "combination",
|
| 208 |
+
"solve", "equation", "inequality", "algebra", "geometry", "triangle",
|
| 209 |
+
"circle", "rectangle", "table", "chart", "graph", "data", "number line",
|
| 210 |
+
"standard deviation", "sum", "product", "difference"
|
| 211 |
+
]
|
| 212 |
+
t = lower_clean(text)
|
| 213 |
+
return any(s in t for s in signals)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def contains_verbal_signal(text: str) -> bool:
|
| 217 |
+
signals = [
|
| 218 |
+
"argument", "assumption", "strengthen", "weaken", "inference",
|
| 219 |
+
"main idea", "tone", "passage", "sentence correction", "grammar",
|
| 220 |
+
"which of the following", "best completes", "critical reasoning",
|
| 221 |
+
"reading comprehension"
|
| 222 |
+
]
|
| 223 |
+
t = lower_clean(text)
|
| 224 |
+
return any(s in t for s in signals)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def asks_for_final_answer(text: str) -> bool:
|
| 228 |
+
t = lower_clean(text)
|
| 229 |
+
patterns = [
|
| 230 |
+
"just give me the answer",
|
| 231 |
+
"give me the answer",
|
| 232 |
+
"what is the answer",
|
| 233 |
+
"which option",
|
| 234 |
+
"which answer",
|
| 235 |
+
"tell me the answer",
|
| 236 |
+
"final answer",
|
| 237 |
+
"correct answer",
|
| 238 |
+
"pick the answer",
|
| 239 |
+
"just answer it",
|
| 240 |
+
]
|
| 241 |
+
return any(p in t for p in patterns)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def asks_for_hint(text: str) -> bool:
|
| 245 |
+
t = lower_clean(text)
|
| 246 |
+
patterns = [
|
| 247 |
+
"hint", "nudge", "don't tell me", "do not tell me", "guide me",
|
| 248 |
+
"help me solve", "walk me through", "step by step", "how do i solve"
|
| 249 |
+
]
|
| 250 |
+
return any(p in t for p in patterns)
|
| 251 |
+
|
| 252 |
|
| 253 |
+
def numeric_from_text(s: str) -> Optional[float]:
|
| 254 |
+
s = s.strip()
|
| 255 |
+
s = s.replace(",", "")
|
| 256 |
+
s = s.replace("%", "")
|
| 257 |
+
if re.fullmatch(r'-?\d+(\.\d+)?', s):
|
| 258 |
+
return float(s)
|
| 259 |
+
val = safe_eval(s)
|
| 260 |
+
return val
|
| 261 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
|
| 263 |
+
def build_style(tone: float, verbosity: float, transparency: float) -> Dict[str, Any]:
|
| 264 |
+
tone = clamp(tone, 0.0, 1.0)
|
| 265 |
+
verbosity = clamp(verbosity, 0.0, 1.0)
|
| 266 |
+
transparency = clamp(transparency, 0.0, 1.0)
|
| 267 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
if tone < 0.33:
|
| 269 |
+
tone_prefix = "Let's keep it focused."
|
| 270 |
elif tone < 0.66:
|
| 271 |
+
tone_prefix = "Let's work through it."
|
| 272 |
else:
|
| 273 |
+
tone_prefix = "You've got this - let's break it down."
|
| 274 |
|
| 275 |
+
if verbosity < 0.34:
|
| 276 |
+
detail = "short"
|
| 277 |
+
elif verbosity < 0.67:
|
| 278 |
+
detail = "medium"
|
| 279 |
+
else:
|
| 280 |
+
detail = "long"
|
| 281 |
|
| 282 |
+
show_steps = transparency >= 0.45
|
|
|
|
|
|
|
| 283 |
|
| 284 |
+
return {
|
| 285 |
+
"tone_prefix": tone_prefix,
|
| 286 |
+
"detail": detail,
|
| 287 |
+
"show_steps": show_steps,
|
| 288 |
+
}
|
| 289 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
|
| 291 |
+
def decide_help_mode(req: ChatRequest) -> str:
|
| 292 |
+
msg = lower_clean(req.message)
|
| 293 |
|
| 294 |
+
if asks_for_hint(msg):
|
| 295 |
+
return "hint"
|
| 296 |
+
if asks_for_final_answer(msg):
|
| 297 |
+
return "answer"
|
|
|
|
| 298 |
|
| 299 |
+
if req.transparency >= 0.8:
|
| 300 |
+
return "answer"
|
| 301 |
+
if req.transparency <= 0.25:
|
| 302 |
+
return "hint"
|
| 303 |
+
return "guided"
|
| 304 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
|
| 306 |
+
def build_context_question(req: ChatRequest) -> str:
|
| 307 |
+
msg = normalize_text(req.message)
|
| 308 |
+
if len(msg) > 25 and ("?" in msg or contains_math_signal(msg) or contains_verbal_signal(msg)):
|
| 309 |
+
return msg
|
| 310 |
|
| 311 |
+
history_blob = last_n_messages(req.chat_history, n=8)
|
| 312 |
+
return normalize_text(history_blob + "\nUSER: " + msg).strip()
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
# =========================================================
|
| 316 |
+
# Math-Verify helpers
|
| 317 |
+
# =========================================================
|
| 318 |
+
|
| 319 |
+
def build_gold_from_options(
|
| 320 |
+
answer_letter: Optional[str],
|
| 321 |
+
answer_value: Optional[str],
|
| 322 |
+
options: List[Tuple[str, str]]
|
| 323 |
+
) -> Optional[str]:
|
| 324 |
+
if answer_value:
|
| 325 |
+
return str(answer_value)
|
| 326 |
+
|
| 327 |
+
if answer_letter and options:
|
| 328 |
+
for letter, raw in options:
|
| 329 |
+
if letter.upper() == answer_letter.upper():
|
| 330 |
+
return raw.strip()
|
| 331 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
return None
|
| 333 |
|
| 334 |
|
| 335 |
+
def verify_solver_answer_with_math_verify(
|
| 336 |
+
predicted_answer: Optional[str],
|
| 337 |
+
gold_answer: Optional[str]
|
| 338 |
+
) -> Dict[str, Any]:
|
| 339 |
+
if not MATH_VERIFY_AVAILABLE:
|
| 340 |
+
return {
|
| 341 |
+
"used": False,
|
| 342 |
+
"verified": None,
|
| 343 |
+
"error": "math-verify not installed"
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
if not predicted_answer or not gold_answer:
|
| 347 |
+
return {
|
| 348 |
+
"used": False,
|
| 349 |
+
"verified": None,
|
| 350 |
+
"error": "missing predicted_answer or gold_answer"
|
| 351 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
+
try:
|
| 354 |
+
pred_parsed = parse(str(predicted_answer))
|
| 355 |
+
gold_parsed = parse(str(gold_answer))
|
| 356 |
+
verified = verify(gold_parsed, pred_parsed)
|
| 357 |
+
|
| 358 |
+
return {
|
| 359 |
+
"used": True,
|
| 360 |
+
"verified": bool(verified),
|
| 361 |
+
"predicted_answer": str(predicted_answer),
|
| 362 |
+
"gold_answer": str(gold_answer),
|
| 363 |
+
"error": None
|
| 364 |
+
}
|
| 365 |
+
except Exception as e:
|
| 366 |
+
return {
|
| 367 |
+
"used": True,
|
| 368 |
+
"verified": None,
|
| 369 |
+
"predicted_answer": str(predicted_answer),
|
| 370 |
+
"gold_answer": str(gold_answer),
|
| 371 |
+
"error": str(e)
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
# =========================================================
|
| 376 |
+
# Option matching
|
| 377 |
+
# =========================================================
|
| 378 |
+
|
| 379 |
+
def find_matching_option(
|
| 380 |
+
value: float,
|
| 381 |
+
options: List[Tuple[str, str]],
|
| 382 |
+
percent_mode: bool = False
|
| 383 |
+
) -> Optional[str]:
|
| 384 |
+
for letter, raw in options:
|
| 385 |
+
raw_clean = raw.strip()
|
| 386 |
+
if percent_mode:
|
| 387 |
+
raw_num = numeric_from_text(raw_clean.replace("%", ""))
|
| 388 |
else:
|
| 389 |
+
raw_num = numeric_from_text(raw_clean)
|
| 390 |
+
if raw_num is None:
|
| 391 |
+
continue
|
| 392 |
+
if abs(raw_num - value) < 1e-6:
|
| 393 |
+
return letter
|
| 394 |
+
return None
|
| 395 |
|
| 396 |
+
|
| 397 |
+
# =========================================================
|
| 398 |
+
# Quant solvers
|
| 399 |
+
# =========================================================
|
| 400 |
+
|
| 401 |
+
def solve_direct_expression(text: str) -> Optional[SolveResult]:
|
| 402 |
+
expr_match = re.search(
|
| 403 |
+
r'(?i)(?:what is|compute|calculate|evaluate)\s+([0-9\.\+\-\*\/\^\(\)\s]+)\??',
|
| 404 |
+
text
|
| 405 |
+
)
|
| 406 |
+
if not expr_match:
|
| 407 |
+
return None
|
| 408 |
+
|
| 409 |
+
expr = expr_match.group(1).strip()
|
| 410 |
+
value = safe_eval(expr)
|
| 411 |
+
if value is None:
|
| 412 |
+
return None
|
| 413 |
+
|
| 414 |
+
return SolveResult(
|
| 415 |
+
solved=True,
|
| 416 |
+
answer_value=format_number(value),
|
| 417 |
+
confidence=0.9,
|
| 418 |
+
method="direct arithmetic",
|
| 419 |
+
reasoning=[
|
| 420 |
+
f"Evaluate the expression {expr}.",
|
| 421 |
+
f"The result is {format_number(value)}."
|
| 422 |
+
]
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def solve_percent_problem(text: str) -> Optional[SolveResult]:
|
| 427 |
+
t = lower_clean(text)
|
| 428 |
+
|
| 429 |
+
m = re.search(r'(\d+(?:\.\d+)?)\s*(?:increased|increase|rose|rises|grows|grew)\s+by\s+(\d+(?:\.\d+)?)\s*%', t)
|
| 430 |
+
if m:
|
| 431 |
+
start = float(m.group(1))
|
| 432 |
+
pct = float(m.group(2))
|
| 433 |
+
result = start * (1 + pct / 100.0)
|
| 434 |
+
return SolveResult(
|
| 435 |
+
solved=True,
|
| 436 |
+
answer_value=format_number(result),
|
| 437 |
+
confidence=0.8,
|
| 438 |
+
method="percent increase",
|
| 439 |
+
reasoning=[
|
| 440 |
+
f"Start with {format_number(start)}.",
|
| 441 |
+
f"Increase by {pct}%, so multiply by {format_number(1 + pct / 100.0)}.",
|
| 442 |
+
f"Result = {format_number(result)}."
|
| 443 |
+
]
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
m = re.search(r'(\d+(?:\.\d+)?)\s*(?:decreased|decrease|fell|drops|dropped)\s+by\s+(\d+(?:\.\d+)?)\s*%', t)
|
| 447 |
+
if m:
|
| 448 |
+
start = float(m.group(1))
|
| 449 |
+
pct = float(m.group(2))
|
| 450 |
+
result = start * (1 - pct / 100.0)
|
| 451 |
+
return SolveResult(
|
| 452 |
+
solved=True,
|
| 453 |
+
answer_value=format_number(result),
|
| 454 |
+
confidence=0.8,
|
| 455 |
+
method="percent decrease",
|
| 456 |
+
reasoning=[
|
| 457 |
+
f"Start with {format_number(start)}.",
|
| 458 |
+
f"Decrease by {pct}%, so multiply by {format_number(1 - pct / 100.0)}.",
|
| 459 |
+
f"Result = {format_number(result)}."
|
| 460 |
+
]
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
m = re.search(r'what percent of\s+(\d+(?:\.\d+)?)\s+is\s+(\d+(?:\.\d+)?)', t)
|
| 464 |
+
if m:
|
| 465 |
+
a = float(m.group(1))
|
| 466 |
+
b = float(m.group(2))
|
| 467 |
+
if a != 0:
|
| 468 |
+
result = (b / a) * 100
|
| 469 |
+
return SolveResult(
|
| 470 |
+
solved=True,
|
| 471 |
+
answer_value=format_number(result) + "%",
|
| 472 |
+
confidence=0.85,
|
| 473 |
+
method="percent comparison",
|
| 474 |
+
reasoning=[
|
| 475 |
+
f"Percent = part / whole × 100 = {format_number(b)}/{format_number(a)} × 100.",
|
| 476 |
+
f"Result = {format_number(result)}%."
|
| 477 |
+
]
|
| 478 |
)
|
| 479 |
|
| 480 |
+
return None
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def solve_ratio_total(text: str) -> Optional[SolveResult]:
|
| 484 |
+
t = lower_clean(text)
|
| 485 |
+
|
| 486 |
+
m = re.search(r'ratio of [a-z ]*?(\d+)\s*:\s*(\d+).*?total(?: is| of)?\s*(\d+(?:\.\d+)?)', t)
|
| 487 |
+
if not m:
|
| 488 |
+
m = re.search(r'(\d+)\s*:\s*(\d+).*?total(?: is| of)?\s*(\d+(?:\.\d+)?)', t)
|
| 489 |
+
if not m:
|
| 490 |
+
return None
|
| 491 |
+
|
| 492 |
+
a = float(m.group(1))
|
| 493 |
+
b = float(m.group(2))
|
| 494 |
+
total = float(m.group(3))
|
| 495 |
+
unit = total / (a + b)
|
| 496 |
+
x = a * unit
|
| 497 |
+
y = b * unit
|
| 498 |
+
|
| 499 |
+
return SolveResult(
|
| 500 |
+
solved=True,
|
| 501 |
+
answer_value=f"{format_number(x)} and {format_number(y)}",
|
| 502 |
+
confidence=0.75,
|
| 503 |
+
method="ratio split",
|
| 504 |
+
reasoning=[
|
| 505 |
+
f"Total parts = {format_number(a)} + {format_number(b)} = {format_number(a + b)}.",
|
| 506 |
+
f"Each part = {format_number(total)}/{format_number(a + b)} = {format_number(unit)}.",
|
| 507 |
+
f"The two quantities are {format_number(x)} and {format_number(y)}."
|
| 508 |
+
]
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def solve_average_problem(text: str) -> Optional[SolveResult]:
|
| 513 |
+
t = lower_clean(text)
|
| 514 |
+
nums = [float(x) for x in re.findall(r'-?\d+(?:\.\d+)?', t)]
|
| 515 |
+
|
| 516 |
+
if ("average" in t or "mean" in t) and re.search(r'(average|mean) of', t) and len(nums) >= 2:
|
| 517 |
+
result = sum(nums) / len(nums)
|
| 518 |
+
return SolveResult(
|
| 519 |
+
solved=True,
|
| 520 |
+
answer_value=format_number(result),
|
| 521 |
+
confidence=0.6,
|
| 522 |
+
method="mean",
|
| 523 |
+
reasoning=[
|
| 524 |
+
f"Add the numbers: {format_number(sum(nums))}.",
|
| 525 |
+
f"Divide by the count: {len(nums)}.",
|
| 526 |
+
f"Mean = {format_number(result)}."
|
| 527 |
+
]
|
| 528 |
)
|
| 529 |
+
|
| 530 |
+
if "median" in t and len(nums) >= 2:
|
| 531 |
+
result = statistics.median(nums)
|
| 532 |
+
return SolveResult(
|
| 533 |
+
solved=True,
|
| 534 |
+
answer_value=format_number(result),
|
| 535 |
+
confidence=0.6,
|
| 536 |
+
method="median",
|
| 537 |
+
reasoning=[
|
| 538 |
+
f"Sort the numbers and take the middle value(s).",
|
| 539 |
+
f"Median = {format_number(result)}."
|
| 540 |
+
]
|
| 541 |
)
|
| 542 |
+
|
| 543 |
+
if "range" in t and len(nums) >= 2:
|
| 544 |
+
result = max(nums) - min(nums)
|
| 545 |
+
return SolveResult(
|
| 546 |
+
solved=True,
|
| 547 |
+
answer_value=format_number(result),
|
| 548 |
+
confidence=0.6,
|
| 549 |
+
method="range",
|
| 550 |
+
reasoning=[
|
| 551 |
+
f"Range = max - min = {format_number(max(nums))} - {format_number(min(nums))}.",
|
| 552 |
+
f"Range = {format_number(result)}."
|
| 553 |
+
]
|
| 554 |
)
|
| 555 |
|
| 556 |
+
return None
|
| 557 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
|
| 559 |
+
def solve_probability_problem(text: str) -> Optional[SolveResult]:
|
| 560 |
+
t = lower_clean(text)
|
| 561 |
+
|
| 562 |
+
if "probability" in t and "out of" in t:
|
| 563 |
+
m = re.search(r'probability.*?(\d+)\s+out of\s+(\d+)', t)
|
| 564 |
+
if m:
|
| 565 |
+
a = float(m.group(1))
|
| 566 |
+
b = float(m.group(2))
|
| 567 |
+
if b != 0:
|
| 568 |
+
p = a / b
|
| 569 |
+
return SolveResult(
|
| 570 |
+
solved=True,
|
| 571 |
+
answer_value=format_fraction_or_decimal(p),
|
| 572 |
+
confidence=0.6,
|
| 573 |
+
method="basic probability",
|
| 574 |
+
reasoning=[
|
| 575 |
+
f"Probability = favorable / total = {int(a)}/{int(b)}.",
|
| 576 |
+
f"That is {format_fraction_or_decimal(p)}."
|
| 577 |
+
]
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
if "probability" in t and ("red" in t or "blue" in t or "green" in t):
|
| 581 |
+
counts = [int(x) for x in re.findall(r'\b\d+\b', t)]
|
| 582 |
+
if len(counts) >= 2:
|
| 583 |
+
total = sum(counts)
|
| 584 |
+
fav = counts[0]
|
| 585 |
+
if total != 0:
|
| 586 |
+
p = fav / total
|
| 587 |
+
return SolveResult(
|
| 588 |
+
solved=True,
|
| 589 |
+
answer_value=format_fraction_or_decimal(p),
|
| 590 |
+
confidence=0.45,
|
| 591 |
+
method="basic probability heuristic",
|
| 592 |
+
reasoning=[
|
| 593 |
+
f"Treat the first quantity as favorable: {fav}.",
|
| 594 |
+
f"Total items = {total}.",
|
| 595 |
+
f"Probability = {fav}/{total} = {format_fraction_or_decimal(p)}."
|
| 596 |
+
],
|
| 597 |
+
caution="This used a simple heuristic. Check the wording carefully."
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
return None
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def sympify_loose(expr: str, symbols: Dict[str, Any]):
|
| 604 |
+
expr = expr.replace("^", "**")
|
| 605 |
+
expr = re.sub(r'(\d)([a-zA-Z])', r'\1*\2', expr)
|
| 606 |
+
expr = re.sub(r'([a-zA-Z])(\d)', r'\1*\2', expr)
|
| 607 |
+
expr = re.sub(r'([a-zA-Z])\(', r'\1*(', expr)
|
| 608 |
+
return sp.sympify(expr, locals=symbols)
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def solve_algebra_with_sympy(text: str) -> Optional[SolveResult]:
|
| 612 |
+
if not SYMPY_AVAILABLE:
|
| 613 |
+
return None
|
| 614 |
+
|
| 615 |
+
raw = normalize_text(text)
|
| 616 |
+
lc = raw.lower()
|
| 617 |
+
|
| 618 |
+
if not re.search(r'\b[a-z]\b', lc):
|
| 619 |
+
return None
|
| 620 |
+
|
| 621 |
+
target_var = "x"
|
| 622 |
+
m_target = re.search(r'solve for\s+([a-z])', lc)
|
| 623 |
+
if m_target:
|
| 624 |
+
target_var = m_target.group(1)
|
| 625 |
+
|
| 626 |
+
eq_lines = []
|
| 627 |
+
for line in raw.splitlines():
|
| 628 |
+
if "=" in line and re.search(r'[a-zA-Z]', line):
|
| 629 |
+
eq_lines.append(line.strip())
|
| 630 |
+
|
| 631 |
+
if not eq_lines:
|
| 632 |
+
eq_lines = re.findall(r'([A-Za-z0-9\+\-\*/\^\(\) ]+=[A-Za-z0-9\+\-\*/\^\(\) ]+)', raw)
|
| 633 |
+
|
| 634 |
+
if not eq_lines:
|
| 635 |
+
return None
|
| 636 |
+
|
| 637 |
+
try:
|
| 638 |
+
symbol_names = sorted(set(re.findall(r'\b[a-z]\b', lc)))
|
| 639 |
+
if not symbol_names:
|
| 640 |
+
symbol_names = ["x"]
|
| 641 |
+
|
| 642 |
+
symbols = {name: sp.symbols(name) for name in symbol_names}
|
| 643 |
+
|
| 644 |
+
equations = []
|
| 645 |
+
for eq in eq_lines:
|
| 646 |
+
left, right = eq.split("=", 1)
|
| 647 |
+
left = sympify_loose(left, symbols)
|
| 648 |
+
right = sympify_loose(right, symbols)
|
| 649 |
+
equations.append(sp.Eq(left, right))
|
| 650 |
+
|
| 651 |
+
vars_to_solve = list(symbols.values())
|
| 652 |
+
sol = sp.solve(equations, vars_to_solve, dict=True)
|
| 653 |
+
|
| 654 |
+
if not sol:
|
| 655 |
+
return None
|
| 656 |
+
|
| 657 |
+
sol0 = sol[0]
|
| 658 |
+
if target_var in symbols and symbols[target_var] in sol0:
|
| 659 |
+
ans = sol0[symbols[target_var]]
|
| 660 |
+
return SolveResult(
|
| 661 |
+
solved=True,
|
| 662 |
+
answer_value=str(ans),
|
| 663 |
+
confidence=0.85,
|
| 664 |
+
method="symbolic algebra",
|
| 665 |
+
reasoning=[
|
| 666 |
+
"Translate the relationships into equation form.",
|
| 667 |
+
"Solve the system symbolically.",
|
| 668 |
+
f"{target_var} = {ans}."
|
| 669 |
+
]
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
parts = [f"{str(k)} = {str(v)}" for k, v in sol0.items()]
|
| 673 |
+
return SolveResult(
|
| 674 |
+
solved=True,
|
| 675 |
+
answer_value=", ".join(parts),
|
| 676 |
+
confidence=0.75,
|
| 677 |
+
method="symbolic algebra",
|
| 678 |
+
reasoning=[
|
| 679 |
+
"Translate the relationships into equations.",
|
| 680 |
+
"Solve the system symbolically.",
|
| 681 |
+
"Solution: " + ", ".join(parts)
|
| 682 |
+
]
|
| 683 |
)
|
| 684 |
+
except Exception:
|
| 685 |
+
return None
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def solve_geometry_heuristic(text: str) -> Optional[SolveResult]:
|
| 689 |
+
t = lower_clean(text)
|
| 690 |
+
|
| 691 |
+
if "rectangle" in t and "area" in t:
|
| 692 |
+
nums = [float(x) for x in re.findall(r'\d+(?:\.\d+)?', t)]
|
| 693 |
+
if len(nums) >= 2:
|
| 694 |
+
area = nums[0] * nums[1]
|
| 695 |
+
return SolveResult(
|
| 696 |
+
solved=True,
|
| 697 |
+
answer_value=format_number(area),
|
| 698 |
+
confidence=0.55,
|
| 699 |
+
method="rectangle area",
|
| 700 |
+
reasoning=[
|
| 701 |
+
f"Area of rectangle = length × width = {format_number(nums[0])} × {format_number(nums[1])} = {format_number(area)}."
|
| 702 |
+
]
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
if "triangle" in t and "area" in t:
|
| 706 |
+
nums = [float(x) for x in re.findall(r'\d+(?:\.\d+)?', t)]
|
| 707 |
+
if len(nums) >= 2:
|
| 708 |
+
area = 0.5 * nums[0] * nums[1]
|
| 709 |
+
return SolveResult(
|
| 710 |
+
solved=True,
|
| 711 |
+
answer_value=format_number(area),
|
| 712 |
+
confidence=0.5,
|
| 713 |
+
method="triangle area",
|
| 714 |
+
reasoning=[
|
| 715 |
+
f"Area of triangle = 1/2 × base × height = 1/2 × {format_number(nums[0])} × {format_number(nums[1])} = {format_number(area)}."
|
| 716 |
+
]
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
if "circle" in t:
|
| 720 |
+
nums = [float(x) for x in re.findall(r'\d+(?:\.\d+)?', t)]
|
| 721 |
+
if "radius" in t and nums:
|
| 722 |
+
r = nums[0]
|
| 723 |
+
if "circumference" in t:
|
| 724 |
+
c = 2 * math.pi * r
|
| 725 |
+
return SolveResult(
|
| 726 |
+
solved=True,
|
| 727 |
+
answer_value=format_number(c),
|
| 728 |
+
confidence=0.6,
|
| 729 |
+
method="circle circumference",
|
| 730 |
+
reasoning=[
|
| 731 |
+
f"Circumference = 2πr = 2π({format_number(r)}) = {format_number(c)}."
|
| 732 |
+
]
|
| 733 |
+
)
|
| 734 |
+
if "area" in t:
|
| 735 |
+
a = math.pi * r * r
|
| 736 |
+
return SolveResult(
|
| 737 |
+
solved=True,
|
| 738 |
+
answer_value=format_number(a),
|
| 739 |
+
confidence=0.6,
|
| 740 |
+
method="circle area",
|
| 741 |
+
reasoning=[
|
| 742 |
+
f"Area = πr² = π({format_number(r)}²) = {format_number(a)}."
|
| 743 |
+
]
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
return None
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def solve_option_match(text: str, options: List[Tuple[str, str]]) -> Optional[SolveResult]:
|
| 750 |
+
if not options:
|
| 751 |
+
return None
|
| 752 |
+
|
| 753 |
+
direct = solve_direct_expression(text)
|
| 754 |
+
if direct and direct.answer_value is not None:
|
| 755 |
+
val = numeric_from_text(direct.answer_value)
|
| 756 |
+
if val is not None:
|
| 757 |
+
letter = find_matching_option(val, options)
|
| 758 |
+
if letter:
|
| 759 |
+
direct.answer_letter = letter
|
| 760 |
+
direct.confidence = max(direct.confidence, 0.95)
|
| 761 |
+
direct.reasoning.append(f"That matches option {letter}.")
|
| 762 |
+
return direct
|
| 763 |
+
|
| 764 |
+
candidates = [
|
| 765 |
+
solve_percent_problem(text),
|
| 766 |
+
solve_ratio_total(text),
|
| 767 |
+
solve_average_problem(text),
|
| 768 |
+
solve_probability_problem(text),
|
| 769 |
+
solve_algebra_with_sympy(text),
|
| 770 |
+
solve_geometry_heuristic(text),
|
| 771 |
+
]
|
| 772 |
+
candidates = [c for c in candidates if c and c.answer_value]
|
| 773 |
+
|
| 774 |
+
for cand in candidates:
|
| 775 |
+
val = numeric_from_text(str(cand.answer_value).replace("%", ""))
|
| 776 |
+
if val is None:
|
| 777 |
+
continue
|
| 778 |
+
|
| 779 |
+
if "%" in str(cand.answer_value):
|
| 780 |
+
letter = find_matching_option(val, options, percent_mode=True)
|
| 781 |
+
else:
|
| 782 |
+
letter = find_matching_option(val, options)
|
| 783 |
+
|
| 784 |
+
if letter:
|
| 785 |
+
cand.answer_letter = letter
|
| 786 |
+
cand.reasoning.append(f"That matches option {letter}.")
|
| 787 |
+
cand.confidence = max(cand.confidence, 0.9)
|
| 788 |
+
return cand
|
| 789 |
|
| 790 |
+
return None
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
def solve_quant(text: str, options: List[Tuple[str, str]]) -> Optional[SolveResult]:
|
| 794 |
+
solvers = [
|
| 795 |
+
solve_option_match,
|
| 796 |
+
lambda t, o: solve_direct_expression(t),
|
| 797 |
+
lambda t, o: solve_percent_problem(t),
|
| 798 |
+
lambda t, o: solve_ratio_total(t),
|
| 799 |
+
lambda t, o: solve_average_problem(t),
|
| 800 |
+
lambda t, o: solve_probability_problem(t),
|
| 801 |
+
lambda t, o: solve_algebra_with_sympy(t),
|
| 802 |
+
lambda t, o: solve_geometry_heuristic(t),
|
| 803 |
+
]
|
| 804 |
+
|
| 805 |
+
for solver in solvers:
|
| 806 |
+
try:
|
| 807 |
+
result = solver(text, options)
|
| 808 |
+
if result and result.solved:
|
| 809 |
+
return result
|
| 810 |
+
except Exception:
|
| 811 |
+
continue
|
| 812 |
+
|
| 813 |
+
return None
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
# =========================================================
|
| 817 |
+
# Verbal strategy
|
| 818 |
+
# =========================================================
|
| 819 |
+
|
| 820 |
+
def solve_verbal_strategy(text: str, options: List[Tuple[str, str]]) -> SolveResult:
|
| 821 |
+
t = lower_clean(text)
|
| 822 |
+
|
| 823 |
+
if "strengthen" in t:
|
| 824 |
+
reasoning = [
|
| 825 |
+
"Find the conclusion and the assumption behind it.",
|
| 826 |
+
"Choose the option that makes that assumption more believable."
|
| 827 |
+
]
|
| 828 |
+
elif "weaken" in t:
|
| 829 |
+
reasoning = [
|
| 830 |
+
"Find the conclusion and the assumption it depends on.",
|
| 831 |
+
"Choose the option that attacks that assumption or gives an alternative explanation."
|
| 832 |
+
]
|
| 833 |
+
elif "assumption" in t:
|
| 834 |
+
reasoning = [
|
| 835 |
+
"Look for the gap between the evidence and the conclusion.",
|
| 836 |
+
"The correct answer is something the argument must assume."
|
| 837 |
+
]
|
| 838 |
+
elif "inference" in t:
|
| 839 |
+
reasoning = [
|
| 840 |
+
"Pick the option that must be true based only on the passage.",
|
| 841 |
+
"Avoid answers that are plausible but not guaranteed."
|
| 842 |
+
]
|
| 843 |
+
elif "sentence correction" in t or "grammar" in t:
|
| 844 |
+
reasoning = [
|
| 845 |
+
"Check grammar, meaning, concision, and parallel structure.",
|
| 846 |
+
"Eliminate answers that distort meaning or break grammar."
|
| 847 |
+
]
|
| 848 |
+
else:
|
| 849 |
+
reasoning = [
|
| 850 |
+
"Identify the question type first.",
|
| 851 |
+
"Eliminate answers that are too extreme, off-topic, or unsupported."
|
| 852 |
+
]
|
| 853 |
+
|
| 854 |
+
return SolveResult(
|
| 855 |
+
solved=False,
|
| 856 |
+
confidence=0.35,
|
| 857 |
+
method="verbal strategy",
|
| 858 |
+
reasoning=reasoning,
|
| 859 |
+
caution="Verbal support here is strategy-first. Quant/Data Insight is stronger in this version."
|
| 860 |
+
)
|
| 861 |
|
| 862 |
+
|
| 863 |
+
# =========================================================
|
| 864 |
+
# Reply composition
|
| 865 |
+
# =========================================================
|
| 866 |
+
|
| 867 |
+
def compose_quant_reply(
|
| 868 |
+
req: ChatRequest,
|
| 869 |
+
result: SolveResult,
|
| 870 |
+
help_mode: str,
|
| 871 |
+
style: Dict[str, Any],
|
| 872 |
+
options: List[Tuple[str, str]]
|
| 873 |
+
) -> str:
|
| 874 |
+
prefix = style["tone_prefix"]
|
| 875 |
+
short = style["detail"] == "short"
|
| 876 |
+
long = style["detail"] == "long"
|
| 877 |
+
|
| 878 |
+
lines = [prefix]
|
| 879 |
+
|
| 880 |
+
if help_mode == "hint":
|
| 881 |
+
lines.append("Hint:")
|
| 882 |
+
if result.reasoning:
|
| 883 |
+
lines.append(result.reasoning[0])
|
| 884 |
+
if len(result.reasoning) > 1 and not short:
|
| 885 |
+
lines.append(result.reasoning[1])
|
| 886 |
+
if options:
|
| 887 |
+
lines.append("Then compare your result with the answer choices.")
|
| 888 |
+
return "\n".join(lines)
|
| 889 |
+
|
| 890 |
+
if help_mode == "guided":
|
| 891 |
+
lines.append(f"I think the method is **{result.method}**.")
|
| 892 |
+
if style["show_steps"]:
|
| 893 |
+
steps = result.reasoning[:2] if short else result.reasoning
|
| 894 |
+
lines.extend([f"- {s}" for s in steps])
|
| 895 |
+
|
| 896 |
+
if result.answer_letter and result.answer_value:
|
| 897 |
+
if long:
|
| 898 |
+
lines.append(f"So the value is **{result.answer_value}**, which matches **option {result.answer_letter}**.")
|
| 899 |
+
else:
|
| 900 |
+
lines.append(f"I get **{result.answer_value}** -> **{result.answer_letter}**.")
|
| 901 |
+
elif result.answer_value:
|
| 902 |
+
lines.append(f"I get **{result.answer_value}**.")
|
| 903 |
+
|
| 904 |
+
if result.caution:
|
| 905 |
+
lines.append(f"Check: {result.caution}")
|
| 906 |
+
return "\n".join(lines)
|
| 907 |
+
|
| 908 |
+
if result.answer_letter and result.answer_value:
|
| 909 |
+
lines.append(f"**Answer: {result.answer_letter}**")
|
| 910 |
+
if style["show_steps"] or long:
|
| 911 |
+
lines.append(f"Value: **{result.answer_value}**")
|
| 912 |
+
steps = result.reasoning[:2] if short else result.reasoning
|
| 913 |
+
lines.extend([f"- {s}" for s in steps])
|
| 914 |
+
elif result.answer_value:
|
| 915 |
+
lines.append(f"**Answer: {result.answer_value}**")
|
| 916 |
+
if style["show_steps"] or long:
|
| 917 |
+
steps = result.reasoning[:2] if short else result.reasoning
|
| 918 |
+
lines.extend([f"- {s}" for s in steps])
|
| 919 |
+
|
| 920 |
+
if result.caution:
|
| 921 |
+
lines.append(f"Check: {result.caution}")
|
| 922 |
+
|
| 923 |
+
return "\n".join(lines)
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
def compose_verbal_reply(
|
| 927 |
+
req: ChatRequest,
|
| 928 |
+
result: SolveResult,
|
| 929 |
+
help_mode: str,
|
| 930 |
+
style: Dict[str, Any],
|
| 931 |
+
options: List[Tuple[str, str]]
|
| 932 |
+
) -> str:
|
| 933 |
+
prefix = style["tone_prefix"]
|
| 934 |
+
lines = [prefix]
|
| 935 |
+
|
| 936 |
+
if help_mode == "answer":
|
| 937 |
+
lines.append("I can help analyse the verbal logic, but this version is strongest on Quant/Data Insight.")
|
| 938 |
+
else:
|
| 939 |
+
lines.append("Here’s the best way to approach this verbal question:")
|
| 940 |
+
|
| 941 |
+
steps = result.reasoning[:2] if style["detail"] == "short" else result.reasoning
|
| 942 |
+
lines.extend([f"- {s}" for s in steps])
|
| 943 |
+
|
| 944 |
+
if options:
|
| 945 |
+
lines.append("Send the full passage plus all answer choices and I can help eliminate them one by one.")
|
| 946 |
+
|
| 947 |
+
if result.caution:
|
| 948 |
+
lines.append(result.caution)
|
| 949 |
+
|
| 950 |
+
return "\n".join(lines)
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
def compose_fallback_reply(req: ChatRequest, style: Dict[str, Any]) -> str:
|
| 954 |
+
prefix = style["tone_prefix"]
|
| 955 |
+
detail = style["detail"]
|
| 956 |
+
|
| 957 |
+
if detail == "short":
|
| 958 |
return (
|
| 959 |
+
f"{prefix}\n"
|
| 960 |
+
"Paste the full GMAT question and answer choices. I’m strongest on Quant/Data Insight and can give a hint or final answer."
|
| 961 |
)
|
| 962 |
|
| 963 |
return (
|
| 964 |
+
f"{prefix}\n"
|
| 965 |
+
"Paste the full GMAT-style question, ideally with answer choices A-E.\n"
|
| 966 |
+
"I can handle:\n"
|
| 967 |
+
"- arithmetic, percentages, ratios, algebra, basic statistics, probability, geometry\n"
|
| 968 |
+
"- option checking for multiple-choice quant questions\n"
|
| 969 |
+
"- strategy help for verbal questions\n"
|
| 970 |
+
"You can also say whether you want a hint, a walkthrough, or just the final answer."
|
| 971 |
)
|
| 972 |
|
| 973 |
|
| 974 |
+
# =========================================================
|
| 975 |
+
# Main chat logic
|
| 976 |
+
# =========================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
| 977 |
|
| 978 |
+
def answer_chat(req: ChatRequest) -> ChatResponse:
|
| 979 |
+
style = build_style(req.tone, req.verbosity, req.transparency)
|
| 980 |
+
help_mode = decide_help_mode(req)
|
| 981 |
|
| 982 |
+
question_text = build_context_question(req)
|
| 983 |
+
options = extract_options(question_text)
|
| 984 |
+
stem = strip_options(question_text) if options else question_text
|
| 985 |
|
| 986 |
+
if contains_math_signal(question_text):
|
| 987 |
+
quant_result = solve_quant(stem, options)
|
| 988 |
+
if quant_result:
|
| 989 |
+
predicted_final = quant_result.answer_value
|
| 990 |
+
gold_final = build_gold_from_options(
|
| 991 |
+
quant_result.answer_letter,
|
| 992 |
+
quant_result.answer_value,
|
| 993 |
+
options
|
| 994 |
+
)
|
| 995 |
|
| 996 |
+
verification = verify_solver_answer_with_math_verify(
|
| 997 |
+
predicted_answer=predicted_final,
|
| 998 |
+
gold_answer=gold_final
|
| 999 |
+
)
|
| 1000 |
|
| 1001 |
+
reply = compose_quant_reply(req, quant_result, help_mode, style, options)
|
| 1002 |
+
|
| 1003 |
+
return ChatResponse(
|
| 1004 |
+
reply=reply,
|
| 1005 |
+
meta={
|
| 1006 |
+
"domain": "quant",
|
| 1007 |
+
"solved": quant_result.solved,
|
| 1008 |
+
"method": quant_result.method,
|
| 1009 |
+
"confidence": quant_result.confidence,
|
| 1010 |
+
"answer_letter": quant_result.answer_letter,
|
| 1011 |
+
"answer_value": quant_result.answer_value,
|
| 1012 |
+
"help_mode": help_mode,
|
| 1013 |
+
"math_verify": verification
|
| 1014 |
+
}
|
| 1015 |
+
)
|
| 1016 |
+
|
| 1017 |
+
if contains_verbal_signal(question_text):
|
| 1018 |
+
verbal_result = solve_verbal_strategy(question_text, options)
|
| 1019 |
+
reply = compose_verbal_reply(req, verbal_result, help_mode, style, options)
|
| 1020 |
+
return ChatResponse(
|
| 1021 |
+
reply=reply,
|
| 1022 |
+
meta={
|
| 1023 |
+
"domain": "verbal",
|
| 1024 |
+
"solved": False,
|
| 1025 |
+
"method": verbal_result.method,
|
| 1026 |
+
"confidence": verbal_result.confidence,
|
| 1027 |
+
"help_mode": help_mode
|
| 1028 |
+
}
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
return ChatResponse(
|
| 1032 |
+
reply=compose_fallback_reply(req, style),
|
| 1033 |
+
meta={
|
| 1034 |
+
"domain": "fallback",
|
| 1035 |
+
"solved": False,
|
| 1036 |
+
"help_mode": help_mode
|
| 1037 |
+
}
|
| 1038 |
+
)
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
# =========================================================
|
| 1042 |
+
# Routes
|
| 1043 |
+
# =========================================================
|
| 1044 |
+
|
| 1045 |
+
@app.get("/health")
|
| 1046 |
+
def health():
|
| 1047 |
+
return {
|
| 1048 |
+
"ok": True,
|
| 1049 |
+
"service": "GMAT Solver v2",
|
| 1050 |
+
"sympy_available": SYMPY_AVAILABLE,
|
| 1051 |
+
"math_verify_available": MATH_VERIFY_AVAILABLE
|
| 1052 |
+
}
|
| 1053 |
|
| 1054 |
|
| 1055 |
+
@app.post("/chat", response_model=ChatResponse)
|
| 1056 |
+
def chat(req: ChatRequest):
|
| 1057 |
+
return answer_chat(req)
|
| 1058 |
+
|
| 1059 |
+
|
| 1060 |
+
@app.get("/", response_class=HTMLResponse)
|
| 1061 |
+
def root():
|
| 1062 |
+
return HTMLResponse("""
|
| 1063 |
+
<!DOCTYPE html>
|
| 1064 |
+
<html>
|
| 1065 |
+
<head>
|
| 1066 |
+
<meta charset="utf-8" />
|
| 1067 |
+
<title>GMAT Solver v2</title>
|
| 1068 |
+
<style>
|
| 1069 |
+
body { font-family: Arial, sans-serif; margin: 24px; max-width: 900px; }
|
| 1070 |
+
textarea, input[type="range"] { width: 100%; }
|
| 1071 |
+
textarea { min-height: 220px; margin-bottom: 12px; }
|
| 1072 |
+
.row { margin-bottom: 12px; }
|
| 1073 |
+
.label { font-weight: bold; margin-bottom: 4px; display: block; }
|
| 1074 |
+
button { padding: 10px 16px; cursor: pointer; }
|
| 1075 |
+
pre {
|
| 1076 |
+
white-space: pre-wrap;
|
| 1077 |
+
background: #f5f5f5;
|
| 1078 |
+
padding: 12px;
|
| 1079 |
+
border-radius: 8px;
|
| 1080 |
+
}
|
| 1081 |
+
</style>
|
| 1082 |
+
</head>
|
| 1083 |
+
<body>
|
| 1084 |
+
<h1>GMAT Solver v2</h1>
|
| 1085 |
+
<p>Paste a GMAT-style question below. You can ask for a hint, a walkthrough, or the final answer.</p>
|
| 1086 |
+
|
| 1087 |
+
<div class="row">
|
| 1088 |
+
<label class="label">Question / Message</label>
|
| 1089 |
+
<textarea id="message">A store increases the price of a jacket from 80 by 25 percent. What is the new price?
|
| 1090 |
+
A) 90
|
| 1091 |
+
B) 95
|
| 1092 |
+
C) 100
|
| 1093 |
+
D) 105
|
| 1094 |
+
E) 110
|
| 1095 |
+
|
| 1096 |
+
Give me the answer.</textarea>
|
| 1097 |
+
</div>
|
| 1098 |
+
|
| 1099 |
+
<div class="row">
|
| 1100 |
+
<label class="label">Tone: <span id="toneVal">0.5</span></label>
|
| 1101 |
+
<input id="tone" type="range" min="0" max="1" step="0.01" value="0.5" oninput="toneVal.textContent=this.value" />
|
| 1102 |
+
</div>
|
| 1103 |
+
|
| 1104 |
+
<div class="row">
|
| 1105 |
+
<label class="label">Verbosity: <span id="verbVal">0.5</span></label>
|
| 1106 |
+
<input id="verbosity" type="range" min="0" max="1" step="0.01" value="0.5" oninput="verbVal.textContent=this.value" />
|
| 1107 |
+
</div>
|
| 1108 |
+
|
| 1109 |
+
<div class="row">
|
| 1110 |
+
<label class="label">Transparency: <span id="transVal">0.5</span></label>
|
| 1111 |
+
<input id="transparency" type="range" min="0" max="1" step="0.01" value="0.5" oninput="transVal.textContent=this.value" />
|
| 1112 |
+
</div>
|
| 1113 |
+
|
| 1114 |
+
<div class="row">
|
| 1115 |
+
<button onclick="send()">Send</button>
|
| 1116 |
+
</div>
|
| 1117 |
+
|
| 1118 |
+
<h3>Response</h3>
|
| 1119 |
+
<pre id="output"></pre>
|
| 1120 |
+
|
| 1121 |
+
<script>
|
| 1122 |
+
async function send() {
|
| 1123 |
+
const payload = {
|
| 1124 |
+
message: document.getElementById('message').value,
|
| 1125 |
+
chat_history: [],
|
| 1126 |
+
tone: parseFloat(document.getElementById('tone').value),
|
| 1127 |
+
verbosity: parseFloat(document.getElementById('verbosity').value),
|
| 1128 |
+
transparency: parseFloat(document.getElementById('transparency').value)
|
| 1129 |
+
};
|
| 1130 |
+
|
| 1131 |
+
const out = document.getElementById('output');
|
| 1132 |
+
out.textContent = "Loading...";
|
| 1133 |
+
|
| 1134 |
+
try {
|
| 1135 |
+
const res = await fetch('/chat', {
|
| 1136 |
+
method: 'POST',
|
| 1137 |
+
headers: {'Content-Type': 'application/json'},
|
| 1138 |
+
body: JSON.stringify(payload)
|
| 1139 |
+
});
|
| 1140 |
+
const data = await res.json();
|
| 1141 |
+
out.textContent = JSON.stringify(data, null, 2);
|
| 1142 |
+
} catch (err) {
|
| 1143 |
+
out.textContent = "Error: " + err;
|
| 1144 |
+
}
|
| 1145 |
+
}
|
| 1146 |
+
</script>
|
| 1147 |
+
</body>
|
| 1148 |
+
</html>
|
| 1149 |
+
""")
|
| 1150 |
+
|
| 1151 |
+
|
| 1152 |
+
# =========================================================
|
| 1153 |
+
# Optional local run
|
| 1154 |
+
# =========================================================
|
| 1155 |
+
# For local testing:
|
| 1156 |
+
# uvicorn app:app --reload --host 0.0.0.0 --port 7860
|