wyr: fix JSON parsing failure causing silent no-op after 'Generating...'
Switch to api/chat with a system prompt for better JSON compliance, and use regex extraction to find the JSON object even if the model wraps it in extra text or markdown fences. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+21
-9
@@ -1542,23 +1542,35 @@ async def check_scramble_answer(client: AsyncClient, room_id: str, sender: str,
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def _generate_wyr() -> dict | None:
|
||||
prompt = (
|
||||
"Generate a fun 'Would You Rather' question with exactly two options. "
|
||||
"Respond with ONLY valid JSON, no markdown: "
|
||||
'{"question": "Would you rather...", "option_a": "...", "option_b": "..."}. '
|
||||
"Keep each option short (under 10 words). Make it fun and interesting."
|
||||
system_msg = (
|
||||
"You are a game host generating Would You Rather questions. "
|
||||
"Always respond with ONLY a JSON object — no markdown fences, no explanation. "
|
||||
'Format: {"question": "Would you rather...", "option_a": "short option", "option_b": "short option"}'
|
||||
)
|
||||
user_msg = "Generate a fun, creative Would You Rather question. Keep each option under 10 words."
|
||||
try:
|
||||
timeout = aiohttp.ClientTimeout(total=20)
|
||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||
async with session.post(
|
||||
f"{OLLAMA_URL}/api/generate",
|
||||
json={"model": ASK_MODEL, "prompt": prompt, "stream": False},
|
||||
f"{OLLAMA_URL}/api/chat",
|
||||
json={
|
||||
"model": ASK_MODEL,
|
||||
"stream": False,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_msg},
|
||||
{"role": "user", "content": user_msg},
|
||||
],
|
||||
},
|
||||
) as response:
|
||||
data = await response.json()
|
||||
text = data.get("response", "").strip()
|
||||
text = data.get("message", {}).get("content", "").strip()
|
||||
# Strip markdown fences if present
|
||||
if "```" in text:
|
||||
text = text.split("```")[1].lstrip("json").strip()
|
||||
text = re.sub(r"```[a-z]*\n?", "", text).strip()
|
||||
# Extract the first JSON object found in the response
|
||||
m = re.search(r"\{[^{}]+\}", text, re.DOTALL)
|
||||
if m:
|
||||
text = m.group(0)
|
||||
parsed = json.loads(text)
|
||||
q = parsed.get("question", "").strip()
|
||||
a = parsed.get("option_a", "").strip()
|
||||
|
||||
Reference in New Issue
Block a user