from __future__ import annotations from typing import Any, TYPE_CHECKING from yuxi.utils.logging_config import logger if TYPE_CHECKING: from .history import MessageCache class Summarizer: def __init__(self, message_cache: MessageCache | None = None): self._trigger_patterns = [ "summarize", "catch up", "tldr", "summary", "what did i miss", "summarise", ] self._message_cache = message_cache def is_summarization_request(self, content: str) -> bool: lowered = content.lower().strip() return any(pattern in lowered for pattern in self._trigger_patterns) def build_summary_request( self, channel_id: str, history: list[dict[str, Any]], chat_type: str = "group", ) -> dict[str, Any]: messages_text = "\n".join(f"[{msg.get('author', 'unknown')}]: {msg.get('content', '')}" for msg in history) system_prompt = ( f"You are summarizing a {chat_type} conversation from an Urbit channel. " f"Provide a concise summary structured as follows:\n" f"(1) Main topics - the key subjects discussed\n" f"(2) Key decisions - any decisions, conclusions, or agreements reached\n" f"(3) Action items - tasks, follow-ups, or next steps mentioned\n" f"(4) Notable participants - key contributors and their roles" ) return { "system_prompt": system_prompt, "channel_id": channel_id, "message_count": len(history), "messages": messages_text, "instruction": ( "Please summarize these messages with the following structure:\n" "1. Main topics\n" "2. Key decisions\n" "3. Action items\n" "4. Notable participants" ), } async def get_recent_history(self, chat_id: str, max_messages: int = 50) -> list[dict[str, Any]]: if not self._message_cache: return [] return await self._message_cache.get_recent(chat_id, max_messages) async def auto_detect_and_respond(self, chat_id: str, content: str) -> dict[str, Any] | None: if not self.is_summarization_request(content): return None history = await self.get_recent_history(chat_id) if not history: logger.info(f"[Urbit] Summarizer: no history available for {chat_id}") return None logger.info(f"[Urbit] Summarizer: detected request in {chat_id}, {len(history)} recent messages") return self.build_summary_request(chat_id, history) def bind_cache(self, message_cache: MessageCache) -> None: self._message_cache = message_cache