Spaces:
Sleeping
Sleeping
Download src/context/context_manager.py from Darshan03/nonllm-chatbot-main: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/spaces/Darshan03/nonllm-chatbot-main/resolve/main/src/context/context_manager.py
- Command line
-
hf download hf://spaces/Darshan03/nonllm-chatbot-main/src/context/context_manager.py
-
curl -L -o context_manager.py https://huggingface.co/spaces/Darshan03/nonllm-chatbot-main/resolve/main/src/context/context_manager.py
14 kB
| """ | |
| Context Manager | |
| --------------- | |
| Maintains a lightweight, session-scoped conversation context window. | |
| Key design decisions | |
| ~~~~~~~~~~~~~~~~~~~~ | |
| - Sliding window of **last 3** intents, entities, and questions (deque maxlen=3). | |
| - Persisted to ``artifacts/sessions/<session_id>.json`` for cross-session memory. | |
| - Loaded back from disk on session restore (Gradio page reload / CLI --session-id). | |
| - ``history_enabled`` flag lets the user turn context off at any time. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import time | |
| import uuid | |
| from collections import deque | |
| from dataclasses import dataclass, field, asdict | |
| from pathlib import Path | |
| from typing import Optional, Any | |
| logger = logging.getLogger(__name__) | |
| # Where session files are persisted (relative to project root) | |
| _DEFAULT_SESSIONS_DIR = Path("artifacts/sessions") | |
| CONTEXT_WINDOW_SIZE = 3 # Keep last N intents / entities / questions | |
| from .topic_stack import HierarchicalTopicTracker, TopicFrame | |
| from .slot_memory import SlotMemory | |
| from .coreference_rewriter import CoreferenceRewriter | |
| from .intent_prior import IntentTransitionPrior | |
| from .turn_record import TurnRecord | |
| # --------------------------------------------------------------------------- | |
| # Data structures | |
| # --------------------------------------------------------------------------- | |
| class ConversationContext: | |
| """Session context window supporting legacy sliding deques and advanced state tracking.""" | |
| session_id: str = field(default_factory=lambda: str(uuid.uuid4())) | |
| history_enabled: bool = True | |
| # --- Legacy Rolling Windows (preserved for backward compatibility) --- | |
| recent_intents: list[str] = field(default_factory=list) | |
| recent_entities: list[str] = field(default_factory=list) | |
| recent_questions: list[str] = field(default_factory=list) | |
| active_topic: Optional[str] = None | |
| # --- New Advanced Context State Extensions --- | |
| topic_stack: list[dict[str, Any]] = field(default_factory=list) | |
| slot_memory: dict[str, str] = field(default_factory=dict) | |
| turn_history: list[dict[str, Any]] = field(default_factory=list) | |
| created_at: float = field(default_factory=time.time) | |
| last_activity_at: float = field(default_factory=time.time) | |
| ttl_seconds: float = 1800.0 # 30-minute inactivity decay | |
| def slots(self) -> dict[str, str]: | |
| """Convenience property alias for slot_memory.""" | |
| return self.slot_memory | |
| def to_dict(self) -> dict: | |
| return asdict(self) | |
| def from_dict(cls, data: dict) -> "ConversationContext": | |
| # Ensure compatibility with old session JSON files lacking new fields | |
| allowed_fields = {f.name for f in cls.__dataclass_fields__.values()} | |
| filtered = {k: v for k, v in data.items() if k in allowed_fields} | |
| return cls(**filtered) | |
| # --------------------------------------------------------------------------- | |
| # Manager | |
| # --------------------------------------------------------------------------- | |
| class ContextManager: | |
| """ | |
| Manages a :class:`ConversationContext` for a single session. | |
| Provides hierarchical topic tracking, slot memory, and intelligent query rewriting. | |
| """ | |
| def __init__( | |
| self, | |
| context: Optional[ConversationContext] = None, | |
| sessions_dir: Path = _DEFAULT_SESSIONS_DIR, | |
| ) -> None: | |
| self.context = context or ConversationContext() | |
| self.sessions_dir = sessions_dir | |
| self.sessions_dir.mkdir(parents=True, exist_ok=True) | |
| # Work with deques internally; reconstruct from stored lists (Legacy support) | |
| self._intent_window: deque[str] = deque( | |
| self.context.recent_intents[-CONTEXT_WINDOW_SIZE:], | |
| maxlen=CONTEXT_WINDOW_SIZE, | |
| ) | |
| self._entity_window: deque[str] = deque( | |
| self.context.recent_entities[-CONTEXT_WINDOW_SIZE:], | |
| maxlen=CONTEXT_WINDOW_SIZE, | |
| ) | |
| self._question_window: deque[str] = deque( | |
| self.context.recent_questions[-CONTEXT_WINDOW_SIZE:], | |
| maxlen=CONTEXT_WINDOW_SIZE, | |
| ) | |
| # Advanced context engines | |
| self.topic_tracker = HierarchicalTopicTracker.from_dict(self.context.topic_stack) | |
| self.slot_memory = SlotMemory.from_dict(self.context.slot_memory) | |
| self.rewriter = CoreferenceRewriter() | |
| self.intent_prior = IntentTransitionPrior() | |
| # If active_topic was loaded from legacy, ensure it's in topic stack | |
| if self.context.active_topic and not self.topic_tracker.current_topic: | |
| self.topic_tracker.push(self.context.active_topic, "concept") | |
| # ------------------------------------------------------------------ | |
| # Public API | |
| # ------------------------------------------------------------------ | |
| def augment_query(self, user_text: str) -> tuple[str, bool]: | |
| """ | |
| Main entrypoint for advanced coreference rewriting and query augmentation. | |
| Replaces legacy manual prefixing in server.py / app.py. | |
| Returns: | |
| (augmented_text, was_augmented) | |
| """ | |
| if not self.context.history_enabled or self.is_expired(): | |
| return user_text, False | |
| active_topic = self.topic_tracker.current_topic or self.context.active_topic | |
| slots = self.slot_memory.to_dict() | |
| return self.rewriter.rewrite( | |
| user_text=user_text, | |
| active_topic=active_topic, | |
| slots=slots, | |
| ) | |
| def is_expired(self) -> bool: | |
| """Check if context has expired due to user inactivity beyond ttl_seconds.""" | |
| if not self.context.last_activity_at: | |
| return False | |
| return (time.time() - self.context.last_activity_at) > self.context.ttl_seconds | |
| def update( | |
| self, | |
| resolved_intent: str, | |
| resolved_entities: list[str], | |
| question: str, | |
| resolved_keywords: list[str] | None = None, | |
| confidence: float = 1.0, | |
| resolution_type: str = "DIRECT", | |
| rewritten_query: Optional[str] = None, | |
| ) -> None: | |
| """ | |
| Push a new resolved turn into the context window and update topic stack & slots. | |
| """ | |
| # Legacy sliding deques | |
| self._intent_window.append(resolved_intent) | |
| for entity in resolved_entities: | |
| self._entity_window.append(entity) | |
| self._question_window.append(question) | |
| # ------------------------------------------------------------------- | |
| # OLD APPROACH (DEPRECATED): Flat single-string active topic assignment | |
| # ------------------------------------------------------------------- | |
| # if resolved_entities: | |
| # self.context.active_topic = resolved_entities[0] | |
| # elif resolved_keywords: | |
| # self.context.active_topic = resolved_keywords[0] | |
| # ------------------------------------------------------------------- | |
| # ------------------------------------------------------------------- | |
| # NEW ADVANCED APPROACH: Hierarchical Topic Stack, Typed Slots & Turn Records | |
| # ------------------------------------------------------------------- | |
| # 1. Update typed slots (programming language, data structure, etc.) | |
| extracted = self.slot_memory.extract_and_update(question, resolved_entities, resolved_keywords) | |
| # 2. Determine target topic and update topic stack | |
| # A new primary topic is introduced if an entity was newly extracted in this turn | |
| new_primary_topic = ( | |
| extracted.get("oop_concept") | |
| or extracted.get("algorithm") | |
| or extracted.get("data_structure") | |
| or extracted.get("pl_concept") | |
| ) | |
| if not new_primary_topic and resolved_entities: | |
| new_primary_topic = resolved_entities[0] | |
| primary_topic = new_primary_topic or self.context.active_topic or ( | |
| resolved_keywords[0] | |
| if ( | |
| resolved_keywords | |
| and not resolved_keywords[0].lower().startswith( | |
| ("it", "its", "their", "this", "that", "these", "those", "what", "how", "why") | |
| ) | |
| ) | |
| else None | |
| ) | |
| if primary_topic: | |
| self.topic_tracker.push( | |
| topic=primary_topic, | |
| topic_type="concept", | |
| confidence=confidence, | |
| ) | |
| self.context.active_topic = self.topic_tracker.current_topic | |
| # 3. Add to structured turn history | |
| turn_num = len(self.context.turn_history) + 1 | |
| record = TurnRecord( | |
| turn_id=turn_num, | |
| raw_query=question, | |
| rewritten_query=rewritten_query or question, | |
| resolved_intent=resolved_intent, | |
| confidence=confidence, | |
| resolution_type=resolution_type, | |
| entities=resolved_entities, | |
| keywords=resolved_keywords or [], | |
| slots=self.slot_memory.to_dict(), | |
| active_topic=self.context.active_topic, | |
| timestamp=time.time(), | |
| ) | |
| self.context.turn_history.append(record.to_dict()) | |
| self.context.last_activity_at = time.time() | |
| # Sync back to dataclass | |
| self._sync_to_context() | |
| def toggle_history(self, enabled: bool) -> None: | |
| """Enable or disable context-aware resolution.""" | |
| self.context.history_enabled = enabled | |
| def reset(self) -> None: | |
| """Clear all history for this session (does not delete the file).""" | |
| self._intent_window.clear() | |
| self._entity_window.clear() | |
| self._question_window.clear() | |
| self.context.active_topic = None | |
| self.topic_tracker.clear() | |
| self.slot_memory.clear() | |
| self.context.turn_history.clear() | |
| self.context.topic_stack.clear() | |
| self.context.slot_memory.clear() | |
| self._sync_to_context() | |
| logger.info("Context reset for session %s", self.context.session_id) | |
| def save(self) -> Path: | |
| """ | |
| Persist the current context window to | |
| ``<sessions_dir>/<session_id>.json``. | |
| Returns the path of the written file. | |
| """ | |
| path = self._session_path(self.context.session_id) | |
| try: | |
| path.write_text( | |
| json.dumps(self.context.to_dict(), indent=2, ensure_ascii=False), | |
| encoding="utf-8", | |
| ) | |
| logger.debug("Context saved → %s", path) | |
| except OSError as exc: | |
| logger.warning("Failed to save context: %s", exc) | |
| return path | |
| def load(self, session_id: str) -> bool: | |
| """ | |
| Restore a context from disk. | |
| Returns ``True`` if a session file was found and loaded, | |
| ``False`` otherwise. | |
| """ | |
| path = self._session_path(session_id) | |
| if not path.exists(): | |
| logger.info("No saved session found for id=%s", session_id) | |
| return False | |
| try: | |
| data = json.loads(path.read_text(encoding="utf-8")) | |
| self.context = ConversationContext.from_dict(data) | |
| # Rebuild deques | |
| self._intent_window = deque( | |
| self.context.recent_intents[-CONTEXT_WINDOW_SIZE:], | |
| maxlen=CONTEXT_WINDOW_SIZE, | |
| ) | |
| self._entity_window = deque( | |
| self.context.recent_entities[-CONTEXT_WINDOW_SIZE:], | |
| maxlen=CONTEXT_WINDOW_SIZE, | |
| ) | |
| self._question_window = deque( | |
| self.context.recent_questions[-CONTEXT_WINDOW_SIZE:], | |
| maxlen=CONTEXT_WINDOW_SIZE, | |
| ) | |
| # Rebuild advanced engines | |
| self.topic_tracker = HierarchicalTopicTracker.from_dict(self.context.topic_stack) | |
| self.slot_memory = SlotMemory.from_dict(self.context.slot_memory) | |
| if self.context.active_topic and not self.topic_tracker.current_topic: | |
| self.topic_tracker.push(self.context.active_topic, "concept") | |
| logger.info("Context restored for session %s", session_id) | |
| return True | |
| except (json.JSONDecodeError, TypeError, KeyError) as exc: | |
| logger.warning("Failed to load context for %s: %s", session_id, exc) | |
| return False | |
| # ------------------------------------------------------------------ | |
| # Convenience accessors (read-only views) | |
| # ------------------------------------------------------------------ | |
| def recent_intents(self) -> list[str]: | |
| return list(self._intent_window) | |
| def recent_entities(self) -> list[str]: | |
| return list(self._entity_window) | |
| def recent_questions(self) -> list[str]: | |
| return list(self._question_window) | |
| # ------------------------------------------------------------------ | |
| # Internal helpers | |
| # ------------------------------------------------------------------ | |
| def _sync_to_context(self) -> None: | |
| self.context.recent_intents = list(self._intent_window) | |
| self.context.recent_entities = list(self._entity_window) | |
| self.context.recent_questions = list(self._question_window) | |
| self.context.topic_stack = self.topic_tracker.to_dict() | |
| self.context.slot_memory = self.slot_memory.to_dict() | |
| def _session_path(self, session_id: str) -> Path: | |
| # Sanitise session_id to prevent path traversal | |
| if callable(session_id): | |
| session_id = session_id() | |
| session_id = str(session_id) if session_id else "default" | |
| safe_id = "".join(c for c in session_id if c.isalnum() or c in "-_") | |
| return self.sessions_dir / f"{safe_id}.json" | |