from __future__ import annotations import re import time from typing import Iterator from .prompts import PERSONA_TITLES, build_system_prompt from .providers import get_provider from .reactions import recent_exemplars from .retrieval import retrieve PERSONAS = ("son", "spirit", "father") _REF_LINE_RE = re.compile(r"(?mi)^\s*references?:\s*(.+)$") _WHITESPACE_SPLIT = re.compile(r"(\s+)") # Paced-reveal target: ~30 chars per chunk, so with a 40 chars/sec budget each # chunk naturally pauses ~0.75s — a comfortable reading cadence. _CHUNK_TARGET = 30 _CHARS_PER_SECOND = 40.0 def _split_text_and_refs(text: str) -> tuple[str, str]: m = _REF_LINE_RE.search(text) if not m: return text.strip(), "" body = text[: m.start()].rstrip() refs = m.group(1).strip() return body, refs def _reveal_chunks(text: str) -> list[str]: """Break text into word-boundary chunks of roughly _CHUNK_TARGET chars. Concatenating the chunks reproduces the original text exactly. """ if not text: return [] tokens = _WHITESPACE_SPLIT.split(text) out: list[str] = [] cur = "" for tok in tokens: if cur and len(cur) >= _CHUNK_TARGET and tok.isspace(): out.append(cur + tok) cur = "" else: cur += tok if cur: out.append(cur) return out def _merge_consecutive_roles(messages: list[dict]) -> list[dict]: """Fold consecutive same-role messages into one (separated by blank lines). Groq/OpenAI-compatible models dislike rapid same-role turns; merging keeps the narrative flow readable while satisfying strict schemas. """ merged: list[dict] = [] for m in messages: if merged and merged[-1]["role"] == m["role"]: merged[-1]["content"] += "\n\n" + m["content"] else: merged.append({"role": m["role"], "content": m["content"]}) return merged def _plain(content) -> str: if content is None: return "" if isinstance(content, str): return content if isinstance(content, list): return " ".join(filter(None, (_plain(p) for p in content))).strip() if isinstance(content, dict): if isinstance(content.get("text"), str): return content["text"] if "content" in content: return _plain(content["content"]) return str(content) def _stream(persona: str, system: str, messages: list[dict], retrieved: list[dict]) -> Iterator[dict]: """One LLM call; yield progressively-complete state dicts for paced reveal. Yields dicts with keys: persona, title, text, refs, retrieved, final. """ try: full = get_provider().generate(system=system, messages=messages) except Exception as e: full = ( f"(System: the LLM provider is not responding.\n\n" f"**{type(e).__name__}:** {e})" ) body, refs = _split_text_and_refs(full) current = "" for chunk in _reveal_chunks(body): current += chunk yield { "persona": persona, "title": PERSONA_TITLES[persona], "text": current, "refs": "", "retrieved": retrieved, "final": False, } pause = max(0.05, min(0.9, len(chunk) / _CHARS_PER_SECOND)) time.sleep(pause) yield { "persona": persona, "title": PERSONA_TITLES[persona], "text": body, "refs": refs, "retrieved": retrieved, "final": True, } def respond( persona: str, history: list[dict], query: str, *, exemplars: list[str] | None = None, ) -> Iterator[dict]: """Single-persona turn. Generator — yields progressive state until final.""" retrieved = retrieve(query, persona=persona, k=8) if exemplars is None: exemplars = recent_exemplars(persona) system = build_system_prompt(persona, retrieved, exemplars=exemplars) messages = _merge_consecutive_roles( [{"role": m["role"], "content": _plain(m["content"])} for m in history] + [{"role": "user", "content": query}] ) yield from _stream(persona, system, messages, retrieved) def trinity_turn(shared_history: list[dict], query: str) -> Iterator[dict]: """Trinity turn — generator yielding messages from Son → Spirit → Father sequentially. Each Person sees the full shared history AND any contributions from the other Persons that have already been generated in this turn, so they can genuinely respond to one another. """ this_turn: list[dict] = [] for persona in PERSONAS: retrieved = retrieve(query, persona=persona, k=8) exemplars = recent_exemplars(persona) # Build this Person's LLM messages. # - Own past assistant messages → role="assistant" # - User messages → role="user" # - Other Persons' past/current assistant messages → role="user" with "[:] " prefix messages: list[dict] = [] for m in shared_history: role = m.get("role") content = _plain(m.get("content")) if role == "user": messages.append({"role": "user", "content": content}) elif role == "assistant": p = m.get("persona") if p == persona: messages.append({"role": "assistant", "content": content}) else: label = PERSONA_TITLES.get(p, "Another voice") messages.append({"role": "user", "content": f"[{label}:] {content}"}) # Current user turn messages.append({"role": "user", "content": query}) # Other Persons' just-generated contributions in THIS turn for t in this_turn: if t["persona"] != persona: label = PERSONA_TITLES.get(t["persona"], "Another voice") messages.append({"role": "user", "content": f"[{label}:] {t['content']}"}) messages = _merge_consecutive_roles(messages) # Prompt context: summary of what's been said so far this turn transcript = [{"persona": t["persona"], "content": t["content"]} for t in this_turn] system = build_system_prompt( persona, retrieved, exemplars=exemplars, trinity_transcript=transcript, ) final_state = None for state in _stream(persona, system, messages, retrieved): yield state if state.get("final"): final_state = state if final_state: this_turn.append({ "persona": persona, "content": final_state["text"], })