Spaces:
Sleeping
Sleeping
File size: 13,983 Bytes
ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e ddcb55f ef31c8e f72a21b ef31c8e f72a21b | 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 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | """
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
# ---------------------------------------------------------------------------
@dataclass
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
@property
def slots(self) -> dict[str, str]:
"""Convenience property alias for slot_memory."""
return self.slot_memory
def to_dict(self) -> dict:
return asdict(self)
@classmethod
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)
# ------------------------------------------------------------------
@property
def recent_intents(self) -> list[str]:
return list(self._intent_window)
@property
def recent_entities(self) -> list[str]:
return list(self._entity_window)
@property
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"
|