nonllm-chatbot-main / src /context /topic_stack.py
Darshan03's picture
feat: AI Grounded Answer Layer with GPT-4o-mini, Groq Multi-Key Pool & Live Token Tracking
ddcb55f verified
Raw History Blame Contribute Delete
8.92 kB
"""
Hierarchical Topic Stack & Tracker
----------------------------------
Maintains a scoped topic hierarchy for multi-turn conversational reasoning.
Supports topic drill-down, topic shift detection, tangents, and topic resumption.
"""
from __future__ import annotations
import time
import logging
from dataclasses import dataclass, field, asdict
from typing import Optional, Any
logger = logging.getLogger(__name__)
@dataclass
class TopicFrame:
"""A single frame in the hierarchical topic stack."""
topic: str
topic_type: str = "concept" # "algorithm", "data_structure", "concept", "aspect"
aspect: Optional[str] = None # e.g., "time_complexity", "code", "space_complexity"
depth: int = 0
confidence: float = 1.0
turns_active: int = 1
timestamp: float = field(default_factory=time.time)
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "TopicFrame":
return cls(**data)
class HierarchicalTopicTracker:
"""
Manages a stack of topics to allow conversational drill-down and topic shifts.
Examples:
- User: "What is a binary tree?" -> Stack: [binary_tree]
- User: "What is an AVL tree?" -> Drill-down / Subtopic: [binary_tree, avl_tree]
- User: "How do rotations work?" -> Drill-down Aspect: [binary_tree, avl_tree, rotations]
- User: "Now tell me about Dijkstra" -> Topic Shift: [dijkstra]
- User: "Going back to AVL trees" -> Topic Resume: [binary_tree, avl_tree]
"""
def __init__(self, max_depth: int = 5) -> None:
self.max_depth = max_depth
self.stack: list[TopicFrame] = []
@property
def current_topic(self) -> Optional[str]:
"""Return the active topic at the top of the stack."""
return self.stack[-1].topic if self.stack else None
@property
def parent_topic(self) -> Optional[str]:
"""Return the parent topic directly below the current active topic."""
return self.stack[-2].topic if len(self.stack) >= 2 else None
@property
def stack_depth(self) -> int:
"""Return current depth of the topic stack."""
return len(self.stack)
@property
def current_aspect(self) -> Optional[str]:
"""Return the active aspect at the top of the stack."""
return self.stack[-1].aspect if self.stack else None
@property
def topic_path(self) -> list[str]:
"""Return list of topic names from root to top of stack."""
return [frame.topic for frame in self.stack]
def pop(self) -> Optional[TopicFrame]:
"""Pop the current active frame and restore the prior topic."""
return self.stack.pop() if self.stack else None
def shift_topic(
self,
topic: str,
topic_type: str = "concept",
aspect: Optional[str] = None,
confidence: float = 1.0,
) -> TopicFrame:
"""Explicitly reset stack and set a new primary topic."""
clean_topic = topic.strip().lower()
new_frame = TopicFrame(
topic=clean_topic,
topic_type=topic_type,
aspect=aspect,
depth=0,
confidence=confidence,
)
self.stack = [new_frame]
logger.debug(f"Topic explicitly shifted to: {clean_topic}")
return new_frame
def push(
self,
topic: str,
topic_type: str = "concept",
aspect: Optional[str] = None,
confidence: float = 1.0,
) -> TopicFrame:
"""
Push or update a topic on the stack.
Returns the active TopicFrame.
"""
clean_topic = topic.strip().lower()
if not clean_topic:
return self.stack[-1] if self.stack else TopicFrame(topic="")
# Check if topic already exists in stack (Topic Resume)
for i, frame in enumerate(self.stack):
if frame.topic == clean_topic:
# Pop frames above it to resume this topic
self.stack = self.stack[: i + 1]
self.stack[-1].turns_active += 1
if aspect:
self.stack[-1].aspect = aspect
logger.debug(f"Topic resumed: {clean_topic} at depth {i}")
return self.stack[-1]
# Check if this is a sub-aspect or continuation of current topic
if self.stack:
curr = self.stack[-1]
if curr.topic == clean_topic:
curr.turns_active += 1
if aspect:
curr.aspect = aspect
return curr
# Check for drill-down (if topic is related or explicitly scoped or aspect/concept)
if self._is_subtopic(curr.topic, clean_topic) or topic_type in ("aspect", "concept"):
new_frame = TopicFrame(
topic=clean_topic,
topic_type=topic_type,
aspect=aspect,
depth=len(self.stack),
confidence=confidence,
)
if len(self.stack) >= self.max_depth:
self.stack.pop(0)
self.stack.append(new_frame)
logger.debug(f"Topic drill-down: {curr.topic} -> {clean_topic}")
return new_frame
# Otherwise, complete Topic Shift
new_frame = TopicFrame(
topic=clean_topic,
topic_type=topic_type,
aspect=aspect,
depth=0,
confidence=confidence,
)
self.stack = [new_frame]
logger.debug(f"Topic shifted to: {clean_topic}")
return new_frame
def update_aspect(self, aspect: str) -> None:
"""Update aspect of current top topic (e.g. time_complexity)."""
if self.stack:
self.stack[-1].aspect = aspect
def decay_topics(self) -> None:
"""Increment turns active and prune stale topics."""
for frame in self.stack:
frame.turns_active += 1
def clear(self) -> None:
"""Clear topic stack."""
self.stack.clear()
def to_dict(self) -> list[dict[str, Any]]:
return [f.to_dict() for f in self.stack]
@classmethod
def from_dict(cls, data: list[dict[str, Any]], max_depth: int = 5) -> "HierarchicalTopicTracker":
tracker = cls(max_depth=max_depth)
if isinstance(data, list):
tracker.stack = [TopicFrame.from_dict(d) for d in data if isinstance(d, dict)]
return tracker
def _is_subtopic(self, parent: str, candidate: str) -> bool:
"""Heuristic to check if candidate is a subtopic of parent."""
parent_words = set(parent.split())
candidate_words = set(candidate.split())
if parent_words & candidate_words:
return True
subtopic_map = {
# DSA Data Structures
"tree": {"binary_tree", "bst", "avl", "red_black_tree", "trie", "heap", "rotations", "traversal"},
"binary_tree": {"bst", "avl", "traversal", "diameter", "balanced_tree", "rotations"},
"graph": {"dijkstra", "bfs", "dfs", "a_star", "kruskal", "prim", "floyd_warshall", "cycle_detection"},
"sorting": {"quick_sort", "merge_sort", "radix_sort", "bubble_sort", "counting_sort", "custom_comparator"},
"linked_list": {"singly_linked_list", "doubly_linked_list", "circular_linked_list"},
# OOP & Programming Language Concepts (pl_extra.csv)
"oop": {"class", "object", "encapsulation", "abstraction", "inheritance", "polymorphism", "solid"},
"object_oriented_programming": {"class", "object", "encapsulation", "abstraction", "inheritance", "polymorphism", "solid"},
"inheritance": {"diamond_problem", "single", "multiple", "multilevel", "hierarchical", "hybrid", "super", "subclass", "overriding"},
"polymorphism": {"overloading", "overriding", "virtual_function", "dynamic_dispatch", "compile_time", "runtime"},
"class": {"constructor", "destructor", "method", "variable", "static", "instance", "abstract_class", "interface"},
"memory": {"stack", "heap", "pointer", "reference", "garbage_collection", "memory_leak", "cache_locality"},
# Complexity & Platform (extra.csv)
"complexity": {"time_complexity", "space_complexity", "auxiliary_space", "amortized", "big_o", "worst_case", "best_case", "average_case"},
"platform": {"tle", "mle", "runtime_error", "wrong_answer", "fast_io", "constraints"},
}
for k, sub_set in subtopic_map.items():
if k in parent and any(sub in candidate for sub in sub_set):
return True
return False