Download agent1b_coder.py from pylxi/script: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/spaces/pylxi/script/resolve/5b5a20db2bac813ff45ecbca31fe006f0b6e2ecf/agent1b_coder.py
- Command line
-
hf download hf://spaces/pylxi/script@5b5a20db2bac813ff45ecbca31fe006f0b6e2ecf/agent1b_coder.py
-
curl -L -o agent1b_coder.py https://huggingface.co/spaces/pylxi/script/resolve/5b5a20db2bac813ff45ecbca31fe006f0b6e2ecf/agent1b_coder.py
11.3 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). | |
| """ | |
| 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) -> str: | |
| 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. | |
| === 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)} | |
| === 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", | |
| "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", ""), | |
| "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 | |