Spaces:
Sleeping

File size: 11,344 Bytes
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
"""
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