The ConversationHistory class manages conversation context for the RAG engine by maintaining a rolling window of recent query-response pairs. It automatically prunes old entries when the history exceeds the configured limit.
Appends the query-response pair to history as a dictionary: {"query": query, "response": response}
If history length exceeds max_history, removes the oldest entry (index 0)
Maintains FIFO order (first in, first out)
No return value
Example:
history = ConversationHistory(max_history=3)# Add first queryhistory.add_query( "Explain Two Sum", "Two Sum finds pairs that sum to target using hash map.")# Add second queryhistory.add_query( "What's the time complexity?", "O(n) time and O(n) space.")# Add third queryhistory.add_query( "Show me the code", "def twoSum(nums, target): ...")print(len(history.history)) # Output: 3# Add fourth query - oldest entry is removedhistory.add_query( "Any edge cases?", "Handle empty arrays and no solution cases.")print(len(history.history)) # Output: 3 (still at max)
Formatted string containing all query-response pairs in the history. Each pair is formatted as:
User: {query}System: {response}
Returns empty string if history is empty.
Behavior:
Iterates through all entries in history order (oldest to newest)
Formats each entry with “User:” and “System:” prefixes
Joins entries with newlines
Strips trailing whitespace
Example:
history = ConversationHistory(max_history=3)history.add_query( "What is Binary Search?", "Binary search is a O(log n) algorithm for sorted arrays.")history.add_query( "Show example", "def binary_search(arr, target): ...")context = history.get_context()print(context)# Output:# User: What is Binary Search?# System: Binary search is a O(log n) algorithm for sorted arrays.# User: Show example# System: def binary_search(arr, target): ...
from src.DSAAssistant.components.memory_buffer import ConversationHistory# Create history with limit of 3history = ConversationHistory(max_history=3)# Add conversation turnshistory.add_query( "What is dynamic programming?", "Dynamic programming is an optimization technique using memoization.")history.add_query( "Give an example", "Fibonacci sequence: fib(n) = fib(n-1) + fib(n-2)")# Get formatted contextcontext = history.get_context()print(context)# Clear when starting new topichistory.clear()