Thanks — I tried to update the canvas with a version that integrates your prompts exactly, but the automated canvas update failed (technical issue with the editor's regex replacement). I didn’t lose any work — I’ll either retry the canvas update if you want, or you can copy the small, targeted code snippets below into your repo. I’ll also explain exactly what to change so your prompts are used correctly and robustly.
What I changed / will integrate
Use your system / user split exactly as given (system message first, user message second).
Force the model to produce the exact output formats you require:
Topics → numbered Hebrew list (1.. up to 5).
Classification → only the JSON object you specified.
Robust parsing:
Parse numbered Hebrew lists (lines beginning with digits + dot).
Extract the first JSON object from the model response (robust to trailing text).
Preserve the exact contribution text when sent in the user prompt (escape quotes & backslashes).
Validate model output (1–5 topics; classification JSON shape; score ∈ {0,1,2}).
Keep retries & exponential backoff and a short rate delay between calls.
Below are the exact, small helper functions and the key classify_contribution / identify_main_topics snippets to drop into your existing class (these are minimal, safe to paste).
- Robust JSON extraction (paste into your utils)
pythonCopyEditimport json, re
from typing import Optional, Dict
def _extract_first_json(text: str) -> Optional[Dict]:
"""Return the first JSON object found in text, or None."""
# find the first {...} block (non-greedy)
match = re.search(r"(\{.*?\})", text, re.DOTALL)
if not match:
return None
candidate = match.group(1)
try:
return json.loads(candidate)
except json.JSONDecodeError:
# try to trim trailing partial tokens (best-effort)
for end in range(len(candidate), 0, -1):
try:
return json.loads(candidate[:end])
except json.JSONDecodeError:
continue
return None
-
Parse numbered Hebrew list into topics (1..5)
pythonCopyEditdef _parse_numbered_hebrew_list(text: str) -> List[str]:
"""Parse lines like:
- נושא א
- נושא ב
Returns list of topic strings (stripped)."""
lines = text.splitlines()
topics = []
for ln in lines:
ln = ln.strip()
m = re.match(r"^\s*\d+\.?\s*(.+)$", ln)
if m:
topics.append(m.group(1).strip())
if not topics:
fallback: non-empty lines
topics = [ln.strip() for ln in lines if ln.strip()]
return topics[:5] # ensure at most 5
-
Safely insert contribution into your user prompt
Your prompt contains quotes around {contribution}. to avoid JSON / quote problems, escape backslashes and quotes:
pythonCopyEditdef _escape_for_prompt(contribution: str) -> str:
return contribution.replace('\', '\\').replace('"', '\"')
And when formatting the user prompt:
pythonCopyEditcontribution_escaped = _escape_for_prompt(contribution)
user_prompt = CLASSIFY_CONTRIBUTION_USER.format(topics=topics_text, contribution=contribution_escaped)
(If you'd rather change the prompt to not include the surrounding quotes around {contribution}, that's slightly cleaner — then you could safely use json.dumps(contribution) to embed an exact JSON-escaped string.)
- Classification call & validation (core logic)
pythonCopyEditmessages = [
{"role": "system", "content": CLASSIFY_CONTRIBUTION_SYSTEM},
{"role": "user", "content": user_prompt},
]
response_text = self._call_with_retries(messages) # your existing retry wrapper
if response_text is None:
return None
strict: parse JSON and validate structure
json_obj = _extract_first_json(response_text)
if not json_obj or "classifications" not in json_obj or not isinstance(json_obj["classifications"], list):
logger.debug("Invalid classification JSON")
return None
entry = json_obj["classifications"][0]
(optional) check contribution text preserved exactly:
if entry.get("contribution") != contribution:
logger.debug("Contribution text differs from model return; continuing if score exists")
try:
score = int(entry.get("score"))
if score in (0, 1, 2):
return score
except Exception:
return None
- Topics step (key parts)
pythonCopyEdit# after building
full_discussion as you already do:
messages = [
{"role": "system", "content": IDENTIFY_TOPICS_SYSTEM},
{"role": "user", "content": IDENTIFY_TOPICS_USER.format(full_discussion=full_discussion)},
]
response_text = self._call_with_retries(messages)
if response_text is None:
topics = []
else:
topics = _parse_numbered_hebrew_list(response_text)
enforce 1..5
if len(topics) > 5:
topics = topics[:5]
if len(topics) < 1:
# fallback heuristic — never leave empty
topics = [full_discussion[:100]]
Practical suggestions / tips
Temperature = 0 for deterministic, rule-following outputs (you're already doing this — good).
In CLASSIFY_CONTRIBUTION_USER explicitly instruct the model to RETURN ONLY THE JSON (you have that) — keep that strict wording; it helps.
Add unit tests: create a few mock model responses (good JSON, JSON with trailing commentary, plain text with digits) and assert your parser returns the correct outputs.
If your model sometimes returns ״ (Hebrew quotes) or other unicode quote chars around the contribution, your exact-text check may fail — I log and continue if score exists; keep this behavior unless exact match is mandatory.
If you run many contributions, consider parallelizing with a concurrency limiter (e.g., asyncio + Semaphore) but keep rate-limiting and retries; I can provide an async-safe pattern if you want.
Next steps (pick one)
I can retry updating the canvas file so the full integrated script (with the exact prompts embedded) is available in the canvas — say “retry canvas update” and I’ll try again.
Or I can produce a complete patch/PR-style diff you can paste into the repo (I’ll generate it here).
Or I can add unit tests / mock responses for offline testing.
Which would you like?