Lara Monteagudo Tubau commited on
Commit ·
ec3ff21
1
Parent(s): 77b1d4b
Add local heuristic fallback for Agent 0 sectioning
Browse files53 unmodified lines545556575859198 unmodified lines25825926026126226328 unmodified lines29229329429529629729829953 unmodified linesfrom __future__ import annotationsimport jsonfrom pathlib import Pathfrom typing import Optional198 unmodified linesreturn errors# ---------------------------------------------------------------------------# Public API# ---------------------------------------------------------------------------28 unmodified linessystem_prompt = build_system_prompt(dimension_labels)user_prompt = build_user_prompt(turns)raw = call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS)result = _parse_response(raw)sections = result.get("sections", [])overview = result.get("session_overview", "")warnings = _validate_sections(sections, turns)53 unmodified lines545556575859606162198 unmodified lines26126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435528 unmodified lines38438538638738838939039139239339439539639739839940040140240340440540640753 unmodified linesfrom __future__ import annotationsimport jsonimport osimport refrom collections import Counterfrom pathlib import Pathfrom typing import Optional198 unmodified linesreturn errors# ---------------------------------------------------------------------------# Heuristic fallback# ---------------------------------------------------------------------------_BOUNDARY_PATTERNS = [re.compile(r"\b(ok|okay|right|so|well)\b.*\b(move on|next|now|let's)\b", re.I),re.compile(r"\b(now|next|then|after that|at the same time)\b", re.I),re.compile(r"\b(let's|we should|we need to|we have to)\b", re.I),re.compile(r"\b(debug|fix|test|check|review|plan|summary|wrap up|finish)\b", re.I),]def _turn_text(turn: dict) -> str:return f"{turn.get('speaker', '')} {turn.get('text', '')}".strip()def _boundary_score(turn: dict) -> int:text = _turn_text(turn)score = 0for pat in _BOUNDARY_PATTERNS:if pat.search(text):score += 1if len(text) < 20:score += 1return scoredef _heuristic_sections(turns: list[dict]) -> dict:"""Simple local segmentation when the remote LLM is unavailable."""n = len(turns)if n == 0:return {"sections": [], "session_overview": ""}target = TARGET_TURNS_PER_SECTIONmin_size = MIN_TURNS_PER_SECTIONsections = []start_idx = 0section_num = 1while start_idx < n:remaining = n - start_idxif remaining <= target + 5:end_idx = n - 1else:candidate = min(start_idx + target - 1, n - 1)window_start = max(start_idx + min_size - 1, candidate - 5)window_end = min(n - min_size, candidate + 5)best_idx = candidatebest_score = -1for idx in range(window_start, window_end + 1):score = _boundary_score(turns[idx])if score > best_score:best_score = scorebest_idx = idxend_idx = best_idxseg_turns = turns[start_idx : end_idx + 1]label = f"Phase {section_num}"texts = " ".join(t.get("text", "") for t in seg_turns).lower()if any(k in texts for k in ["plan", "planning", "organize", "setup"]):label = f"Planning Phase {section_num}"elif any(k in texts for k in ["debug", "fix", "error", "bug", "issue"]):label = f"Debugging Phase {section_num}"elif any(k in texts for k in ["test", "testing", "try", "check"]):label = f"Testing Phase {section_num}"elif any(k in texts for k in ["review", "reflect", "summary", "wrap up"]):label = f"Review Phase {section_num}"sections.append({"section_id": f"s{section_num:02d}","label": label,"summary": (f"Heuristic local segment covering {len(seg_turns)} turns. "f"Use this as a draft when remote sectioning is unavailable."),"start_turn_id": seg_turns[0]["turn_id"],"end_turn_id": seg_turns[-1]["turn_id"],"start_time": seg_turns[0].get("start_time", ""),"end_time": seg_turns[-1].get("end_time", ""),})start_idx = end_idx + 1section_num += 1overview = f"Local heuristic segmentation created {len(sections)} sections because the remote LLM was unavailable."return {"sections": sections, "session_overview": overview}# ---------------------------------------------------------------------------# Public API# ---------------------------------------------------------------------------28 unmodified linessystem_prompt = build_system_prompt(dimension_labels)user_prompt = build_user_prompt(turns)fallback_requested = os.environ.get("LOCAL_SECTIONING", "").strip().lower() in {"1", "true", "yes", "on"}if fallback_requested:print("[Agent 0] LOCAL_SECTIONING enabled — using heuristic fallback.")result = _heuristic_sections(turns)else:try:raw = call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS)result = _parse_response(raw)except Exception as exc:msg = str(exc).lower()billing_error = any(token in msg for token in ["prepaid", "credit", "billing", "payment", "quota", "insufficient"])if billing_error:print("[Agent 0] Remote LLM billing issue detected — using heuristic fallback.")result = _heuristic_sections(turns)else:raisesections = result.get("sections", [])overview = result.get("session_overview", "")warnings = _validate_sections(sections, turns)
agent0_sectioner.py+110-2