Spaces:
Sleeping

script / agent1_segmenter.py
Lara Monteagudo Tubau
Fix 5 bugs: f-string crash, broken streaming, pending rules filter, chunk dedup, silent discard
ab719c7
Raw History Blame Contribute Delete
14.3 kB
"""
agent1_segmenter.py
-------------------
Agent 1: The Segmenter.
Responsibilities:
- Load Tier 1 library (dimensions, examples, coding rules)
- Load Tier 2 validated learnings (if any exist)
- Receive a window of transcript turns
- Call the Claude API to segment and code each window
- Return structured segments with dimension codes, rationale, confidence,
uncertainty flags, and open/closed boundary status
- Hand back the open segment start position for the next window
Agent 1 must NEVER read Tier 3 (candidate/quarantined learnings).
"""
import json
from pathlib import Path
from typing import Optional
from llm_client import call_llm
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
LIBRARY_ROOT = Path(__file__).parent / "library"
TIER1_PATH = LIBRARY_ROOT / "tier1_core"
TIER2_PATH = LIBRARY_ROOT / "tier2_validated"
MAX_TOKENS = 4000
# Single-pass limit: transcripts up to ~200 turns fit comfortably.
# Beyond this the model takes too long to generate the full JSON response.
SINGLE_PASS_CHAR_LIMIT = 20_000
# Chunk size in turns for longer transcripts
CHUNK_TURNS = 150
# ---------------------------------------------------------------------------
# Library loader
# ---------------------------------------------------------------------------
def load_tier1() -> dict:
"""Load all Tier 1 files. Raises if any file is missing or malformed."""
dimensions = json.loads((TIER1_PATH / "dimensions.json").read_text())
examples = json.loads((TIER1_PATH / "examples.json").read_text())
coding_rules = json.loads((TIER1_PATH / "coding_rules.json").read_text())
return {
"dimensions": dimensions["dimensions"],
"examples": examples["examples"],
"coding_rules": coding_rules["rules"],
}
def load_tier2() -> dict:
"""Load Tier 2 validated learnings. Returns empty structures if not yet populated."""
learned_rules = json.loads((TIER2_PATH / "learned_rules.json").read_text())
edge_cases = json.loads((TIER2_PATH / "edge_cases.json").read_text())
return {
"learned_rules": learned_rules.get("learned_rules", []),
"edge_cases": edge_cases.get("edge_cases", []),
}
# ---------------------------------------------------------------------------
# Prompt builder
# ---------------------------------------------------------------------------
def _format_dimensions(dimensions: list[dict]) -> str:
lines = []
for d in dimensions:
lines.append(f"[{d['id']}] {d['label']}")
lines.append(f" Summary: {d['summary']}")
lines.append(f" Key behavioral markers:")
for marker in d["key_behavioral_markers"]:
lines.append(f" - {marker}")
lines.append("")
return "\n".join(lines)
def _format_examples(examples: list[dict]) -> str:
lines = []
for ex in examples:
lines.append(f"Dimension: {ex['dimension_id']} ({ex['type'].upper()})")
lines.append(f"Label: {ex['label']}")
for turn in ex["exchange"]:
lines.append(f" {turn['speaker']}: {turn['text']}")
lines.append(f"Note: {ex['annotation_note']}")
lines.append("")
return "\n".join(lines)
def _format_rules(rules: list[dict]) -> str:
return "\n".join(
f"[{r['rule_id']}] {r['label']}: {r['description']}"
for r in rules
)
def _format_learned(tier2: dict) -> str:
rules = tier2.get("learned_rules", [])
cases = tier2.get("edge_cases", [])
if not rules and not cases:
return "None yet."
lines = []
for r in rules:
lines.append(f"- LEARNED RULE: {r.get('description', '')}")
for c in cases:
lines.append(f"- EDGE CASE: {c.get('description', '')}")
return "\n".join(lines)
def _format_turns(turns: list[dict]) -> str:
lines = []
for t in turns:
lines.append(
f"[turn_{t['turn_id']}] [{t['start_time']}] {t['speaker']}: {t['text']}"
)
return "\n".join(lines)
def build_system_prompt(tier1: dict, tier2: dict) -> str:
return f"""You are a behavioral coding assistant trained in collaborative learning research.
Your task is to segment a transcript excerpt into episodes and assign each episode
a dimension code from a theory-driven coding framework.
You must follow all coding rules exactly. You may not infer beyond what is
observable in the transcript text.
=== DIMENSION DEFINITIONS ===
{_format_dimensions(tier1['dimensions'])}
=== ANCHOR EXAMPLES ===
{_format_examples(tier1['examples'])}
=== CODING RULES (MANDATORY) ===
{_format_rules(tier1['coding_rules'])}
=== VALIDATED LEARNINGS FROM PRIOR CODING SESSIONS ===
{_format_learned(tier2)}
=== OUTPUT FORMAT ===
You must respond ONLY with a valid JSON object. No preamble, no explanation outside the JSON.
The JSON must follow this exact structure:
{{
"segments": [
{{
"segment_id": "string β€” use format seg_001, seg_002 etc.",
"start_turn_id": integer,
"end_turn_id": integer,
"start_time": "HH:MM:SS",
"end_time": "HH:MM:SS",
"dimension_id": "D1 to D9",
"dimension_label": "string",
"boundary_status": "closed or open",
"confident": true or false,
"uncertain": true or false,
"uncertainty_note": "string or null β€” name competing dimension and why if uncertain",
"rationale": "1-2 sentences citing specific observable behaviors from the turns"
}}
],
"window_summary": {{
"total_turns_processed": integer,
"total_segments_found": integer,
"last_segment_status": "closed or open",
"next_window_start_turn_id": integer or null
}}
}}
If the last segment is OPEN, set next_window_start_turn_id to the start_turn_id
of that open segment. The next window will begin from there.
If the last segment is CLOSED, set next_window_start_turn_id to null.
"""
def build_user_prompt(turns: list[dict]) -> str:
return f"""Please segment and code the following transcript excerpt.
=== TRANSCRIPT TURNS ===
{_format_turns(turns)}
Remember:
- Assign exactly one dimension per segment
- Flag uncertainty if two dimensions are competing
- Mark the last segment as OPEN if the episode is not behaviorally complete
- Base your rationale only on observable turn content
"""
# ---------------------------------------------------------------------------
# API call
# ---------------------------------------------------------------------------
def _call_claude(system_prompt: str, user_prompt: str) -> str:
return call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS)
# ---------------------------------------------------------------------------
# Response parser
# ---------------------------------------------------------------------------
def _parse_response(raw: str) -> dict:
"""
Parse Claude's JSON response. Strips markdown fences if present.
Raises ValueError with details if the response is malformed.
"""
cleaned = raw.strip()
if cleaned.startswith("```"):
cleaned = "\n".join(cleaned.split("\n")[1:])
if cleaned.endswith("```"):
cleaned = "\n".join(cleaned.split("\n")[:-1])
cleaned = cleaned.strip()
try:
parsed = json.loads(cleaned)
except json.JSONDecodeError as e:
raise ValueError(
f"Agent 1 returned invalid JSON.\nError: {e}\nRaw response:\n{raw}"
) from e
# Basic validation
if "segments" not in parsed:
raise ValueError(f"Response missing 'segments' key.\nRaw:\n{raw}")
if "window_summary" not in parsed:
raise ValueError(f"Response missing 'window_summary' key.\nRaw:\n{raw}")
return parsed
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def segment_window(
turns: list[dict],
session_id: str,
window_index: int,
library_root: Optional[Path] = None,
) -> dict:
"""
Segment a window of transcript turns.
Args:
turns: List of turn dicts from transcript_parser.parse_transcript()
session_id: Identifier for this transcript/dyad session
window_index: Which window this is (0-indexed), used for segment ID namespacing
library_root: Override for library path (useful for testing)
Returns:
Dict with keys: segments, window_summary, session_id, window_index
"""
global LIBRARY_ROOT, TIER1_PATH, TIER2_PATH
if library_root:
LIBRARY_ROOT = library_root
TIER1_PATH = library_root / "tier1_core"
TIER2_PATH = library_root / "tier2_validated"
if not turns:
raise ValueError("No turns provided to segment_window.")
# Load library β€” Tier 1 always, Tier 2 always, Tier 3 NEVER
tier1 = load_tier1()
tier2 = load_tier2()
# Build prompts
system_prompt = build_system_prompt(tier1, tier2)
user_prompt = build_user_prompt(turns)
# Call API
raw_response = _call_claude(system_prompt, user_prompt)
# Parse and validate
result = _parse_response(raw_response)
# Namespace segment IDs to avoid collisions across windows
prefix = f"w{window_index:02d}"
for seg in result["segments"]:
seg["segment_id"] = f"{session_id}_{prefix}_{seg['segment_id']}"
result["session_id"] = session_id
result["window_index"] = window_index
return result
def _call_single_pass(
turns: list[dict],
session_id: str,
chunk_index: int,
system_prompt: str,
) -> list[dict]:
"""Send one batch of turns to the LLM and return namespaced segments."""
user_prompt = build_user_prompt(turns)
raw = _call_claude(system_prompt, user_prompt)
result = _parse_response(raw)
prefix = f"c{chunk_index:02d}"
for seg in result["segments"]:
seg["segment_id"] = f"{session_id}_{prefix}_{seg['segment_id']}"
print(f"[Agent 1] Chunk {chunk_index}: {len(result['segments'])} segments "
f"(turns {turns[0]['turn_id']}–{turns[-1]['turn_id']})")
return result["segments"]
def run_full_transcript(
turns: list[dict],
session_id: str,
library_root: Optional[Path] = None,
) -> list[dict]:
"""
Segment an entire transcript.
Strategy:
- Load library once.
- If the formatted transcript fits within SINGLE_PASS_CHAR_LIMIT, send it
in a single LLM call (best context, fewest calls).
- If it exceeds the limit, split into CHUNK_TURNS-turn chunks with a
small overlap so episodes that straddle a boundary are not lost.
Returns:
List of all segments across all chunks, in order.
"""
global LIBRARY_ROOT, TIER1_PATH, TIER2_PATH
if library_root:
LIBRARY_ROOT = library_root
TIER1_PATH = library_root / "tier1_core"
TIER2_PATH = library_root / "tier2_validated"
if not turns:
raise ValueError("No turns provided.")
# Load library once
tier1 = load_tier1()
tier2 = load_tier2()
system_prompt = build_system_prompt(tier1, tier2)
formatted = _format_turns(turns)
# ── Single pass ──────────────────────────────────────────────────────────
if len(formatted) <= SINGLE_PASS_CHAR_LIMIT:
print(f"[Agent 1] Single-pass mode ({len(turns)} turns, "
f"{len(formatted):,} chars)")
return _call_single_pass(turns, session_id, 0, system_prompt)
# ── Chunked fallback ─────────────────────────────────────────────────────
overlap = CHUNK_TURNS // 10 # 10 % overlap between chunks
step = CHUNK_TURNS - overlap
chunks = [turns[i:i + CHUNK_TURNS] for i in range(0, len(turns), step)]
print(f"[Agent 1] Chunked mode ({len(turns)} turns β†’ {len(chunks)} chunks "
f"of ~{CHUNK_TURNS} with {overlap}-turn overlap)")
all_segments: list[dict] = []
# Track covered turn ranges by (start_turn_id, end_turn_id) to deduplicate
# segments from overlapping chunks. Segment IDs cannot be used here because
# each chunk gets a different prefix (c00_, c01_, …), so two segments covering
# identical turns would have different IDs and both be included β€” a real bug
# that creates duplicate coverage of the overlap zone.
seen_turn_ranges: set[tuple[int, int]] = set()
for idx, chunk in enumerate(chunks):
segs = _call_single_pass(chunk, session_id, idx, system_prompt)
for seg in segs:
turn_range = (seg["start_turn_id"], seg["end_turn_id"])
if turn_range not in seen_turn_ranges:
seen_turn_ranges.add(turn_range)
all_segments.append(seg)
print(f"[Agent 1] Complete. Total segments: {len(all_segments)}")
return all_segments
# ---------------------------------------------------------------------------
# Save output
# ---------------------------------------------------------------------------
def save_segments(segments: list[dict], output_path: Path) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(
json.dumps({"segments": segments}, indent=2, ensure_ascii=False),
encoding="utf-8",
)
print(f"[Agent 1] Segments saved to {output_path}")
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import sys
if len(sys.argv) < 3:
print("Usage: python agent1_segmenter.py <parsed_turns.json> <session_id> [output.json]")
sys.exit(1)
turns_file = Path(sys.argv[1])
session_id = sys.argv[2]
output_file = Path(sys.argv[3]) if len(sys.argv) > 3 else Path(f"sessions/{session_id}/segments_proposed.json")
turns = json.loads(turns_file.read_text())
segments = run_full_transcript(turns, session_id)
save_segments(segments, output_file)