Lara Monteagudo Tubau
Fix 5 bugs: f-string crash, broken streaming, pending rules filter, chunk dedup, silent discard
ab719c7 Download pipeline.py from pylxi/script: direct link, hf CLI and curl.
- Browser
- Download file 17.1 kB
-
https://huggingface.co/spaces/pylxi/script/resolve/main/pipeline.py
- Command line
-
hf download hf://spaces/pylxi/script/pipeline.py
-
curl -L -o pipeline.py https://huggingface.co/spaces/pylxi/script/resolve/main/pipeline.py
17.1 kB
| """ | |
| pipeline.py | |
| ----------- | |
| Multi-agent pipeline orchestrator for CollabCode. | |
| Architecture: Parallel Map with Context Chain | |
| ============================================= | |
| βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| Transcript β Agent 0 (1 LLM call, whole transcript) β | |
| ββββββββββββββΊβ Produces: section map + handoff documents β | |
| ββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ | |
| β handoff doc per section | |
| ββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ | |
| β Parallel Agent 1a (N concurrent LLM calls) β | |
| Human confirmsβ Each section: boundary detection with section ctx β | |
| sections ββββΊβ Produces: boundary results + episode handoffs β | |
| ββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ | |
| β boundary handoff per section | |
| ββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββ | |
| β Agent 1b (sequential per section after human review)β | |
| Human adjusts β Coding with boundary context from Agent 1a β | |
| boundaries βββΊβ Produces: coded segments β | |
| βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| Key design patterns | |
| ------------------- | |
| 1. Parallel Map (Agent 1a) | |
| Sections are causally independent β Agent 0 fixes their boundaries | |
| before 1a runs, so 1a sections can execute concurrently. | |
| ThreadPoolExecutor with max_workers=3 limits API rate pressure. | |
| Literature: | |
| Dean & Ghemawat (2004). MapReduce: Simplified data processing on large | |
| clusters. OSDI 2004. β parallel map over independent partitions. | |
| Wu et al. (2023). AutoGen: Enabling next-gen LLM applications via | |
| multi-agent conversation. arXiv:2308.08155. | |
| β concurrent agent execution model. | |
| 2. Context Chain (handoff documents) | |
| Each agent writes a structured memo that the next agent reads. | |
| This reduces cold-start errors at agent handoffs and gives Agent 1b | |
| the boundary rationale rather than starting from zero. | |
| Literature: | |
| Park et al. (2023). Generative agents: Interactive simulacra of | |
| human behavior. UIST 2023. β agents maintain and pass memory | |
| summaries to downstream consumers. | |
| Hong et al. (2023). MetaGPT: Meta programming for multi-agent | |
| collaborative framework. ICLR 2024. | |
| β structured output documents flowing between agents. | |
| Shinn et al. (2023). Reflexion: Language agents with verbal | |
| reinforcement learning. NeurIPS 2023. | |
| β agents build context from prior observations. | |
| 3. Progress streaming | |
| A threading.Queue bridges the parallel worker threads to the | |
| Gradio generator, emitting one yield per completed section. | |
| The researcher sees a live table update rather than a frozen UI. | |
| Literature: | |
| Nielsen, J. (1994). Usability Engineering, ch.8. Academic Press. | |
| β response feedback within 10s required to maintain user flow. | |
| 4. Stats tracking (PipelineStats) | |
| Every call records wall time, estimated tokens, retries, and timeout. | |
| Speedup vs. sequential is computed and shown in the UI. | |
| Literature: | |
| Sigelman et al. (2010). Dapper: A Large-Scale Distributed Systems | |
| Tracing Infrastructure. Google Technical Report. | |
| β distributed tracing for latency analysis. | |
| 5. Circuit-breaker awareness | |
| Workers check llm_client._circuit_breaker before dispatching. | |
| Failed sections are marked ERROR and returned to the researcher | |
| rather than silently dropped or retried indefinitely. | |
| """ | |
| from __future__ import annotations | |
| import queue | |
| import threading | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from dataclasses import dataclass, field | |
| from typing import Callable, Iterator, Optional | |
| from llm_client import call_llm_timed, LLMCallStats, circuit_state | |
| # Maximum parallel workers for Agent 1a. | |
| # 3 balances latency vs. HF Inference API rate limits (typically ~5 req/min | |
| # for free tier; 3 leaves headroom for retries). | |
| MAX_PARALLEL_WORKERS = 3 | |
| # --------------------------------------------------------------------------- | |
| # Data structures | |
| # --------------------------------------------------------------------------- | |
| class SectionResult: | |
| """Outcome of one Agent 1a or Agent 1b call for a single section.""" | |
| section_id: str | |
| section_label: str | |
| success: bool | |
| result: Optional[dict] # the agent's output dict | |
| stats: Optional[LLMCallStats] | |
| wall_time_s: float | |
| error: Optional[str] = None | |
| def status_icon(self) -> str: | |
| if self.success: | |
| return "β" | |
| return "β" | |
| class PipelineStats: | |
| """Aggregate statistics for the full pipeline run.""" | |
| agent_name: str | |
| n_sections: int | |
| results: list[SectionResult] = field(default_factory=list) | |
| parallel_wall_s: float = 0.0 | |
| sequential_est_s: float = 0.0 # what it would have taken serially | |
| def n_success(self) -> int: | |
| return sum(1 for r in self.results if r.success) | |
| def n_error(self) -> int: | |
| return sum(1 for r in self.results if not r.success) | |
| def speedup(self) -> float: | |
| if self.parallel_wall_s <= 0: | |
| return 1.0 | |
| return round(self.sequential_est_s / self.parallel_wall_s, 1) | |
| def total_estimated_tokens(self) -> int: | |
| return sum( | |
| r.stats.estimated_total_tok | |
| for r in self.results | |
| if r.stats and r.success | |
| ) | |
| def summary_line(self) -> str: | |
| spd = f"{self.speedup:.1f}Γ" if self.speedup > 1.1 else "β" | |
| return ( | |
| f"{self.n_success}/{self.n_sections} OK Β· " | |
| f"{self.parallel_wall_s:.0f}s wall Β· " | |
| f"~{self.speedup:.1f}Γ faster than serial Β· " | |
| f"~{self.total_estimated_tokens:,} tokens" | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Handoff document builders | |
| # --------------------------------------------------------------------------- | |
| def build_agent0_section_handoff(section: dict, session_overview: str) -> dict: | |
| """ | |
| Package the context that Agent 0 produces for one section | |
| into the format Agent 1a will consume. | |
| """ | |
| return { | |
| "session_overview": session_overview, | |
| "section_id": section.get("section_id", ""), | |
| "section_label": section.get("label", ""), | |
| "section_summary": section.get("summary", ""), | |
| "start_time": section.get("start_time", ""), | |
| "end_time": section.get("end_time", ""), | |
| } | |
| def build_agent1a_boundary_handoff(section: dict, agent1a_result: dict) -> dict: | |
| """ | |
| Package Agent 1a's boundary analysis for Agent 1b to consume. | |
| Agent 1b receives the boundary rationale and episode distribution so it | |
| can calibrate its coding to the local conversational structure rather | |
| than starting cold (Park et al. 2023 β agent memory passing). | |
| """ | |
| boundaries = agent1a_result.get("boundaries", []) | |
| segments = agent1a_result.get("segments", []) | |
| n_boundaries = len(boundaries) | |
| # Summarise the boundary signals found | |
| signal_counts: dict[str, int] = {} | |
| for b in boundaries: | |
| sig = b.get("boundary_signal", "unknown") | |
| signal_counts[sig] = signal_counts.get(sig, 0) + 1 | |
| signal_summary = "; ".join( | |
| f"{n} {sig.replace('_', ' ')}" for sig, n in signal_counts.items() | |
| ) or "no boundaries β single episode" | |
| # Build short episode previews for Agent 1b context | |
| episode_previews = [] | |
| for seg in segments[:6]: # cap at 6 to avoid prompt bloat | |
| turns = seg.get("turns", []) | |
| if turns: | |
| episode_previews.append({ | |
| "segment_id": seg["segment_id"], | |
| "first_turn": turns[0].get("text", "")[:80], | |
| }) | |
| return { | |
| "section_id": section.get("section_id", ""), | |
| "section_label": section.get("label", ""), | |
| "section_summary": section.get("summary", ""), | |
| "n_boundaries": n_boundaries, | |
| "n_episodes": len(segments), | |
| "boundary_signals": signal_summary, | |
| "episode_previews": episode_previews, | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Parallel Agent 1a runner | |
| # --------------------------------------------------------------------------- | |
| def run_boundaries_parallel( | |
| sections: list[dict], | |
| all_turns: list[dict], | |
| session_id: str, | |
| session_overview: str = "", | |
| max_workers: int = MAX_PARALLEL_WORKERS, | |
| ) -> Iterator[tuple[SectionResult, PipelineStats]]: | |
| """ | |
| Run Agent 1a on all sections concurrently. | |
| Yields (SectionResult, PipelineStats_so_far) after each section completes | |
| so callers can stream progress. The final yield contains the complete stats. | |
| Design | |
| ------ | |
| Uses a threading.Queue to bridge worker threads and the caller's | |
| generator loop (Nielsen 1994 β live feedback prevents perceived freeze). | |
| Workers share a ThreadPoolExecutor; results arrive in completion order, | |
| not submission order (as_completed pattern). | |
| Args | |
| ---- | |
| sections : confirmed section list from Agent 0 + human review. | |
| all_turns : full parsed turn list for the session. | |
| session_id : used for segment ID namespacing. | |
| session_overview : Agent 0's session-level summary (context chain). | |
| max_workers : parallel worker cap (default 3 to respect API limits). | |
| """ | |
| from agent1a_boundary import propose_boundaries_with_context | |
| result_q: queue.Queue[SectionResult | None] = queue.Queue() | |
| t_wall_start = time.perf_counter() | |
| stats = PipelineStats( | |
| agent_name="Agent 1a β Boundary Detector", | |
| n_sections=len(sections), | |
| ) | |
| def _worker(sec: dict) -> None: | |
| turns = [t for t in all_turns | |
| if sec["start_turn_id"] <= t["turn_id"] <= sec["end_turn_id"]] | |
| t0 = time.perf_counter() | |
| handoff_in = build_agent0_section_handoff(sec, session_overview) | |
| try: | |
| result, llm_stats = propose_boundaries_with_context( | |
| section=sec, | |
| turns=turns, | |
| session_id=session_id, | |
| agent0_handoff=handoff_in, | |
| ) | |
| sr = SectionResult( | |
| section_id=sec["section_id"], | |
| section_label=sec.get("label", ""), | |
| success=True, | |
| result=result, | |
| stats=llm_stats, | |
| wall_time_s=round(time.perf_counter() - t0, 1), | |
| ) | |
| except Exception as exc: | |
| sr = SectionResult( | |
| section_id=sec["section_id"], | |
| section_label=sec.get("label", ""), | |
| success=False, | |
| result=None, | |
| stats=None, | |
| wall_time_s=round(time.perf_counter() - t0, 1), | |
| error=str(exc), | |
| ) | |
| result_q.put(sr) | |
| # Dispatch all workers without blocking β results stream into the queue | |
| # as each section completes, so the caller receives live updates. | |
| # (Calling shutdown(wait=True) here would block until ALL workers finish, | |
| # defeating the streaming purpose and freezing the UI for the full batch.) | |
| executor = ThreadPoolExecutor(max_workers=max_workers) | |
| for sec in sections: | |
| executor.submit(_worker, sec) | |
| executor.shutdown(wait=False) # non-blocking: workers run in background | |
| # Yield results in completion order as they arrive in the queue | |
| n_received = 0 | |
| while n_received < len(sections): | |
| try: | |
| sr = result_q.get(timeout=_TIMEOUT_MAX_WAIT) | |
| except queue.Empty: | |
| remaining = len(sections) - n_received | |
| raise RuntimeError( | |
| f"Timed out waiting for {remaining} section result(s) after " | |
| f"{_TIMEOUT_MAX_WAIT}s. The HF Inference API may be overloaded " | |
| "or unreachable. Check your HF_TOKEN and retry." | |
| ) | |
| stats.results.append(sr) | |
| n_received += 1 | |
| if n_received == len(sections): | |
| stats.parallel_wall_s = round(time.perf_counter() - t_wall_start, 1) | |
| stats.sequential_est_s = sum(r.wall_time_s for r in stats.results) | |
| yield sr, stats | |
| _TIMEOUT_MAX_WAIT = 360 # max seconds to wait for any single section result | |
| # --------------------------------------------------------------------------- | |
| # Sequential Agent 1b runner (per-section, after human boundary review) | |
| # --------------------------------------------------------------------------- | |
| def run_coding_with_context( | |
| section: dict, | |
| segments: list[dict], | |
| agent1a_result: Optional[dict] = None, | |
| library_root=None, | |
| ) -> tuple[list[dict], LLMCallStats]: | |
| """ | |
| Run Agent 1b on one section, enriched with Agent 1a's boundary handoff. | |
| Returns (coded_segments, stats). | |
| """ | |
| from agent1b_coder import code_section_with_context | |
| boundary_handoff = ( | |
| build_agent1a_boundary_handoff(section, agent1a_result) | |
| if agent1a_result | |
| else None | |
| ) | |
| return code_section_with_context( | |
| section=section, | |
| segments=segments, | |
| boundary_handoff=boundary_handoff, | |
| library_root=library_root, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Stats rendering (for UI transparency panel) | |
| # --------------------------------------------------------------------------- | |
| def render_pipeline_stats_html(stats: PipelineStats) -> str: | |
| """Render PipelineStats as an HTML block for the UI agent log.""" | |
| rows = "" | |
| for r in stats.results: | |
| tok_str = f"~{r.stats.estimated_total_tok:,}" if r.stats else "β" | |
| time_str = f"{r.wall_time_s:.1f}s" | |
| icon = r.status_icon | |
| icon_col = "#065f46" if r.success else "#be123c" | |
| rows += ( | |
| f'<tr>' | |
| f'<td style="padding:4px 8px;font-weight:600">{r.section_id}</td>' | |
| f'<td style="padding:4px 8px;color:#475569">{r.section_label[:22]}</td>' | |
| f'<td style="padding:4px 8px;font-family:monospace">{time_str}</td>' | |
| f'<td style="padding:4px 8px;font-family:monospace;color:#64748b">{tok_str}</td>' | |
| f'<td style="padding:4px 8px;font-weight:700;color:{icon_col}">{icon}</td>' | |
| f'</tr>' | |
| ) | |
| if not rows: | |
| return "" | |
| speedup_line = "" | |
| if stats.speedup > 1.1: | |
| speedup_line = ( | |
| f'<div style="background:#ecfdf5;border:1px solid #86efac;border-radius:6px;' | |
| f'padding:8px 12px;margin-bottom:8px;font-size:0.82em;color:#065f46">' | |
| f'<strong>β‘ {stats.speedup:.1f}Γ faster</strong> than sequential processing β ' | |
| f'{stats.parallel_wall_s:.0f}s wall vs ~{stats.sequential_est_s:.0f}s serial Β· ' | |
| f'~{stats.total_estimated_tokens:,} tokens total' | |
| f'</div>' | |
| ) | |
| cb_state = circuit_state() | |
| cb_line = "" | |
| if cb_state != "CLOSED": | |
| cb_line = ( | |
| f'<div style="background:#fef2f2;border:1px solid #fca5a5;border-radius:6px;' | |
| f'padding:6px 12px;margin-bottom:6px;font-size:0.8em;color:#991b1b">' | |
| f'β Circuit breaker: <strong>{cb_state}</strong>' | |
| f'</div>' | |
| ) | |
| return ( | |
| f'{cb_line}{speedup_line}' | |
| f'<div style="font-size:0.75em;font-weight:700;text-transform:uppercase;' | |
| f'letter-spacing:0.08em;color:#94a3b8;margin-bottom:6px">' | |
| f'{stats.agent_name}</div>' | |
| f'<table style="border-collapse:collapse;width:100%;font-size:0.8em">' | |
| f'<tr style="background:#f1f5f9;font-size:0.75em;font-weight:600;color:#64748b">' | |
| f'<th style="padding:4px 8px;text-align:left">Section</th>' | |
| f'<th style="padding:4px 8px;text-align:left">Label</th>' | |
| f'<th style="padding:4px 8px;text-align:left">Time</th>' | |
| f'<th style="padding:4px 8px;text-align:left">~Tokens</th>' | |
| f'<th style="padding:4px 8px;text-align:left">OK</th>' | |
| f'</tr>' | |
| f'{rows}</table>' | |
| ) | |