Spaces:
Sleeping

script / agent1b_coder.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
17.4 kB
"""
agent1b_coder.py
----------------
Agent 1b: The Dimension Coder.
Given segments with confirmed boundaries (from Agent 1a + human review),
assigns each segment a dimension code from the D1–D9 framework. Operates
on one topical section at a time, using section context to inform coding.
Rationale for separating coding from segmentation
--------------------------------------------------
See agent1a_boundary.py for the full argument. In brief:
Krippendorff, K. (2004). Content analysis (ch. 7). Sage.
β€” Unitising and categorising are distinct cognitive operations.
Interleaving them in one prompt inflates apparent agreement by
constraining where boundaries can fall to match preferred codes.
Pustejovsky, J., & Stubbs, A. (2012). Natural Language Annotation for
Machine Learning (ch. 4). O'Reilly.
Section context window
----------------------
Providing Agent 1b with the section label and summary (from Agent 0) acts
as a form of "discourse context" shown to improve coding reliability in:
Reidsma, D., & Carletta, J. (2008). Reliability measurement without
limits. Computational Linguistics, 34(3), 319–326.
β€” Annotators with shared discourse context show higher kappa.
Uncertainty-first routing (active learning)
-------------------------------------------
Agent 1b flags segments as uncertain, enabling researchers to prioritise
review of those cases β€” the core insight from uncertainty sampling:
Settles, B. (2012). Active learning. Synthesis Lectures on Artificial
Intelligence and Machine Learning, 6(1), 1–114. Morgan & Claypool.
Monarch, R. (2021). Human-in-the-loop machine learning (ch. 3).
Manning. β€” Confidence-based routing to human review.
Collaborative learning dimension framework
------------------------------------------
The D1–D9 coding scheme implemented here follows the multi-dimensional
quality rating approach established in:
Meier, A., Spada, H., & Rummel, N. (2007). A rating scheme for assessing
the quality of computer-supported collaboration processes.
International Journal of Computer-Supported Collaborative Learning,
2(1), 63–86.
Rummel, N., & Spada, H. (2005). Learning to collaborate: An instructional
approach to promoting collaborative problem solving in computer-mediated
settings. Journal of the Learning Sciences, 14(2), 201–241.
Agent 1b reads Tier 1 (core definitions) and Tier 2 (validated learnings).
Agent 1b NEVER reads Tier 3 (candidate corrections β€” reserved for Agent 2).
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Optional
from llm_client import call_llm
LIBRARY_ROOT = Path(__file__).parent / "library"
TIER1_PATH = LIBRARY_ROOT / "tier1_core"
TIER2_PATH = LIBRARY_ROOT / "tier2_validated"
MAX_TOKENS = 3000
MAX_SEGS_PER_CALL = 8 # batch ceiling β€” prevents context overflow on large sections
# ---------------------------------------------------------------------------
# Library loaders
# ---------------------------------------------------------------------------
def load_tier1() -> dict:
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:
learned_rules = json.loads((TIER2_PATH / "learned_rules.json").read_text())
edge_cases = json.loads((TIER2_PATH / "edge_cases.json").read_text())
return {
# Only active (approved) rules reach Agent 1b
"learned_rules": [
r for r in learned_rules.get("learned_rules", [])
if r.get("active")
],
"edge_cases": edge_cases.get("edge_cases", []),
}
# ---------------------------------------------------------------------------
# Formatters
# ---------------------------------------------------------------------------
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('rule_type')}]: {r.get('description', '')}"
)
for c in cases:
lines.append(f"- EDGE CASE: {c.get('description', '')}")
return "\n".join(lines)
def _format_segment(seg: dict) -> str:
turns = seg.get("turns", [])
lines = [
f"Segment ID: {seg['segment_id']} "
f"({seg.get('start_time', '?')} – {seg.get('end_time', '?')})"
]
for t in turns:
lines.append(f" [{t['turn_id']}] {t['speaker']}: {t['text']}")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Prompt builders
# ---------------------------------------------------------------------------
def build_system_prompt(
tier1: dict,
tier2: dict,
section: dict,
boundary_handoff: dict | None = None,
) -> str:
"""
Build the Agent 1b system prompt, optionally enriched with Agent 1a's
boundary analysis handoff.
Receiving the boundary rationale means Agent 1b knows why each episode
was carved out β€” it can use this to calibrate dimension assignment, e.g.
if a boundary fell on a 'sequence_completion', Agent 1b knows the episode
it is coding represents a self-contained conversational act.
(Hong et al. 2023 MetaGPT β€” structured inter-agent document passing)
"""
boundary_context = ""
if boundary_handoff:
previews = boundary_handoff.get("episode_previews", [])
preview_text = "\n".join(
f" {p['segment_id']}: \"{p['first_turn'][:60]}…\""
for p in previews
) or " (no previews)"
boundary_context = f"""
=== EPISODE STRUCTURE FROM AGENT 1a ===
This section contains {boundary_handoff.get('n_episodes', '?')} episodes
carved by {boundary_handoff.get('n_boundaries', 0)} boundaries.
Boundary signals found: {boundary_handoff.get('boundary_signals', 'none')}
Episode entry points:
{preview_text}
Use this to understand the local conversational rhythm, but base your
dimension assignment solely on observable turn content.
"""
return f"""You are a behavioral coding assistant trained in collaborative learning research.
You are coding segments from one section of a Zoom transcript.
Section context: {section['label']} β€” {section.get('summary', '')}
Use this context to inform your interpretation, but base your final decision
solely on observable turn content.
{boundary_context}
=== DIMENSION DEFINITIONS ===
{_format_dimensions(tier1['dimensions'])}
=== ANCHOR EXAMPLES ===
{_format_examples(tier1['examples'])}
=== CODING RULES (MANDATORY) ===
{_format_rules(tier1['coding_rules'])}
=== VALIDATED LEARNINGS FROM PRIOR SESSIONS ===
{_format_learned(tier2)}
=== SECONDARY DIMENSION (optional β€” use sparingly) ===
Collaborative discourse moves are sometimes genuinely multifunctional.
If an episode PROMINENTLY exhibits a second dimension alongside the primary β€”
not merely as a surface feature but as a sustained behavioral pattern β€”
set secondary_dimension_id to that dimension's ID.
Rules:
- Use secondary ONLY when a second dimension is clearly observable and significant
- Secondary must be different from primary
- Do NOT use secondary instead of uncertain: true (they serve different purposes)
- Most segments will have null secondary_dimension_id
- Valid example: episode primarily about reaching consensus (D4) where speakers
also actively check understanding throughout β†’ D4 primary, D1 secondary
Set secondary_dimension_id to null if no secondary applies. Do not force it.
This follows Strijbos et al. (2006) and Suthers & Rosen (2011): discourse moves
are often multifunctional; forcing a single code loses analytical nuance.
=== OUTPUT FORMAT ===
Respond ONLY with valid JSON. Code ALL segments provided.
{{
"coded_segments": [
{{
"segment_id": "must match input segment_id exactly",
"dimension_id": "D1 to D9",
"dimension_label": "string",
"secondary_dimension_id": "D1 to D9 or null β€” use sparingly",
"secondary_dimension_label":"string or null",
"secondary_rationale": "1 sentence explaining why secondary applies, or null",
"confident": true or false,
"uncertain": true or false,
"uncertainty_note": "competing dimension and why, or null",
"rationale": "1–2 sentences citing specific observable behaviors"
}}
]
}}
"""
def build_user_prompt(segments: list[dict]) -> str:
seg_text = "\n\n".join(_format_segment(s) for s in segments)
return (
f"Please assign a dimension code to each of the following "
f"{len(segments)} segment(s).\n\n{seg_text}\n\n"
"Base rationale only on observable turn content."
)
# ---------------------------------------------------------------------------
# Response parser
# ---------------------------------------------------------------------------
def _parse_response(raw: str) -> list[dict]:
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:
result = json.loads(cleaned)
except json.JSONDecodeError as e:
raise ValueError(
f"Agent 1b returned invalid JSON.\nError: {e}\nRaw:\n{raw}"
) from e
if "coded_segments" not in result:
raise ValueError("Agent 1b response missing 'coded_segments' key.")
return result["coded_segments"]
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def code_section(
section: dict,
segments: list[dict],
library_root: Optional[Path] = None,
) -> list[dict]:
"""
Assign dimension codes to all segments in one confirmed section.
Batches the LLM call if the section has more than MAX_SEGS_PER_CALL
segments, to avoid context overflow with many long turns.
Args:
section: Confirmed section dict (for context window).
segments: Uncoded segment dicts from Agent 1a (boundaries confirmed
by the researcher).
library_root: Override library path (for testing).
Returns:
List of segment dicts with dimension_id, rationale, confident, and
uncertain fields filled. The 'turns' key is preserved for the UI.
"""
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 segments:
return []
print(
f"[Agent 1b] Coding {len(segments)} segments in "
f"{section['section_id']} β€” {section['label']}..."
)
tier1 = load_tier1()
tier2 = load_tier2()
system_prompt = build_system_prompt(tier1, tier2, section)
# Batch into groups to respect context limits
batches = [
segments[i:i + MAX_SEGS_PER_CALL]
for i in range(0, len(segments), MAX_SEGS_PER_CALL)
]
all_coded: dict[str, dict] = {}
for batch_idx, batch in enumerate(batches):
user_prompt = build_user_prompt(batch)
raw = call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS)
coded_batch = _parse_response(raw)
for c in coded_batch:
all_coded[c["segment_id"]] = c
if len(batches) > 1:
print(
f"[Agent 1b] Batch {batch_idx + 1}/{len(batches)} complete "
f"({len(coded_batch)} segments)"
)
# Merge coded fields back into original segment dicts (preserving 'turns')
result = []
for seg in segments:
code = all_coded.get(seg["segment_id"], {})
result.append({
**seg,
"dimension_id": code.get("dimension_id", ""),
"dimension_label": code.get("dimension_label", ""),
"secondary_dimension_id": code.get("secondary_dimension_id"),
"secondary_dimension_label":code.get("secondary_dimension_label"),
"secondary_rationale": code.get("secondary_rationale"),
"confident": code.get("confident", False),
"uncertain": code.get("uncertain", False),
"uncertainty_note": code.get("uncertainty_note"),
"rationale": code.get("rationale", ""),
})
n_uncertain = sum(1 for s in result if s.get("uncertain"))
print(
f"[Agent 1b] {section['section_id']}: {len(result)} segments coded, "
f"{n_uncertain} flagged uncertain β€” route to researcher review."
)
return result
def code_section_with_context(
section: dict,
segments: list[dict],
boundary_handoff: dict | None = None,
library_root=None,
) -> tuple[list[dict], object]:
"""
Context-aware dimension coding β€” for use by pipeline.py.
Same as code_section() but:
1. Accepts an Agent 1a boundary handoff to enrich the system prompt.
2. Returns (coded_segments, llm_stats) for pipeline-level tracking.
The boundary handoff tells Agent 1b how the episodes were carved, so it
can better calibrate dimension assignment to the local conversational
structure (Hong et al. 2023 MetaGPT β€” inter-agent document passing).
"""
from llm_client import call_llm_timed
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 segments:
return [], None
print(
f"[Agent 1b] {section['section_id']} β€” {section.get('label','')} "
f"({len(segments)} segments, boundary_ctx={'yes' if boundary_handoff else 'no'})..."
)
tier1 = load_tier1()
tier2 = load_tier2()
system_prompt = build_system_prompt(tier1, tier2, section,
boundary_handoff=boundary_handoff)
batches = [
segments[i:i + MAX_SEGS_PER_CALL]
for i in range(0, len(segments), MAX_SEGS_PER_CALL)
]
all_coded: dict[str, dict] = {}
last_stats = None
for batch_idx, batch in enumerate(batches):
user_prompt = build_user_prompt(batch)
raw, stats = call_llm_timed(system_prompt, user_prompt, max_tokens=MAX_TOKENS)
last_stats = stats
coded_batch = _parse_response(raw)
for c in coded_batch:
all_coded[c["segment_id"]] = c
if len(batches) > 1:
print(f"[Agent 1b] Batch {batch_idx+1}/{len(batches)} done "
f"({stats.wall_time_s:.1f}s, ~{stats.estimated_total_tok:,} tok)")
result = []
for seg in segments:
code = all_coded.get(seg["segment_id"], {})
result.append({
**seg,
"dimension_id": code.get("dimension_id", ""),
"dimension_label": code.get("dimension_label", ""),
"secondary_dimension_id": code.get("secondary_dimension_id"),
"secondary_dimension_label":code.get("secondary_dimension_label"),
"secondary_rationale": code.get("secondary_rationale"),
"confident": code.get("confident", False),
"uncertain": code.get("uncertain", False),
"uncertainty_note": code.get("uncertainty_note"),
"rationale": code.get("rationale", ""),
})
n_uncertain = sum(1 for s in result if s.get("uncertain"))
wall_str = f"{last_stats.wall_time_s:.1f}s" if last_stats else "?s"
print(
f"[Agent 1b] {section['section_id']}: {len(result)} coded, "
f"{n_uncertain} uncertain ({wall_str})"
)
return result, last_stats