Affective RAG: A Step Beyond Semantic Retrieval into Artificial Episodic Memory
From the publisher’s feed, collected in the ZeroLabs newsroom.
Photo by Numan Ali on UnsplashIntroductionTraditional RAG (Retrieval Augmented Generation) is useful for grounding LLMs (Large Language Models) using external data sources. This reduces “hallucinations” and improves overall response accuracyon topics outside their training data. Standard RAG leverages semantic understanding to choose what information is relevant. This approach is great for fact-based retrieval, but fails to address the nuances of Affective Computing.In the field of Affective Computing, our goal is to enable systems to recognize, interpret, and respond intelligently to human emotion. If we want systems to respond more like humans, then the process by which we retrieve the information used to generate responses must also be similar to how humans do it. The process is called human episodic memory. Episodic memory is defined as “a type of long-term memory that involves conscious recollection of previous experiences together with their context in terms of time, place, and associated emotions” [1]. From this definition, we can derive two insights: 1) recollection occurs as a stream of connected events, and 2) those events are composed of three components: context, emotions, and time.That’s why standard RAG often feels cold and robotic. It often treats memory as isolated data points rather than a continuous human experience. By mimicking the way we recall memories, in hops and order of importance, we can go beyond fact-based recall.To bridge the gap, I introduce the Affective Link Score (ALS), a computational model that measures the strength of a connection between two events as a function of semantic, emotional, and temporal components [2]. Furthermore, I introduce Context Path Traversal (CPT), an information retrieval algorithm that implements ALS as an intelligent scoring criterion for navigating memory graphs and retrieving affectively-grounded event sequences. All code will be provided within the AffectiveRAG GitHub repository and as a Python package for convenience.The Affective Link Score (ALS): Computing AssociationFor a system to intelligently select what events to include as context from an interconnected web of experiences, we need a way to quantify how related two events are. The Affective Link Score (ALS) does this by combining semantic similarity, emotional similarity, emotional intensity, and temporal proximity into a weighted sum with a bias. ALS is computed as:ALS = w₁⋅ S + w₂⋅ E + w₃⋅ I + w₄⋅ T + bwhere wₙ are configurable weights, S is semantic similarity, E is emotional similarity, I is emotional intensity, T is temporal proximity, and b is a scalar bias.Mathematical ReasoningSemantic similarity is the topical anchor that links the content of one event to another. This can be calculated by performing cosine similarity on two semantic embeddings. The value produced is within the range [-1, 1], but a mathematical transform could be applied to bound it to [0, 1].Emotional similarity refers to the degree of alignment between the feelings associated with two events. This can also be calculated using cosine similarity applied to emotional embeddings. Emotional embeddings are similar to semantic embeddings but aim to represent emotional content instead of topical content. These are typically generated using encoder models fine-tuned on affective datasets (e.g., GoEmotions), but can also be extracted in a more compressed form using the VAD (Valence-Arousal-Dominance) model or via semantic transformations of well-curated, emotionally descriptive text. We normalize the range of values for emotional similarity to [0, 1] to match the range of semantic similarity.Emotional intensity is a measure of the strength of the emotions evoked by the event. While emotional similarity measures emotional alignment (direction), it does not capture the strength of the emotion (magnitude). To address this, we incorporate the arousal dimension from the VAD model mentioned previously, yielding a value in the range [0, 1]. Incorporating emotional intensity allows the heuristic to account for emotional impact.Finally, temporal proximity is the time elapsed between the two events, with an inverse function applied to normalize it to [0, 1]. One thing to note is that the units used (seconds, hours, days) will determine how quickly the value decays over time.Memory GraphsNow that we have a way to quantify associations between events, let’s discuss how to model the flow of episodic memory. Recall from earlier that recollection occurs as a stream of events — one event after another. This process is governed by time. In standard RAG, we fetch a flat list of the top-k most topically similar events from a vector database. In this, the narrative flow of time is lost.To regain the flow of time, we shift to a memory graph architecture, where events are represented as nodes, and directed edges capture causal connections between them. Retrieval then becomes a question of graph traversal strategies.Context Path Traversal (CPT)We adopt RAG’s starting point by performing a similarity search to select the top-k seed nodes in the graph to start our traversal from. We create a unique list for each seed node to track the events encounteredduring the traversal. Each resulting pathis referred to as a context path because the nodes along it contribute to the overall context. The following procedure is followed for each node, starting from the seed node, until an exit condition (e.g., no nodes remaining, a maximum depth, or ALS threshold) is reached:Context Accumulation: Append the current node to the list.Weighing: Calculate the ALS for each of the node’s unvisited neighbors.Decisioning: Select the top-n neighbors with the highest ALS to visit next (DFS).Here’s pseudocode for the algorithm:# Context Path Traversaldef context_path_traversal(query, top_k, max_depth): seed_nodes = get_topk_seed_nodes(query, top_k) context_paths = [] # Visit node and accumulate context def visit(cur_node, visited, path, depth): if cur_node in visited or depth > max_depth: return False path.append(cur_node) visited.add(cur_node) selected = select_top_k_als(cur_node.neighbors) for next_node in selected: visit(next_node, visited, path, depth + 1) # Start traversals from seed nodes for node in seed_nodes: visited = set() path = [] visit(node, visited, path, 0)Note: By using Depth First Search, we ensure the algorithm prioritizes narrative flow rather than sporadic inclusion of orderly tangent events.By using the Affective Link Score as an intelligent reranking engine for this traversal, the algorithm effectively filters out semantic noise that would otherwise cause a model to lose the narrative thread. During testing, applying an empirical intensity weight (w₃ = 6.27) enabled the system to achieve 100% recallon multiple-choice narrative causal link tasks. This demonstrates that combining affective weighting and path-based retrieval can solve the “Lost in the Middle” problem that standard RAG cannot.RAG vs. CPT VisualizedFigure 1: A comparison between traditional RAG and CPT. Standard RAG retrieves isolated events with high semantic similarity, whereas CPT explores the memory graph to reconstruct affective and time-aware sequences.At the end, we have k context paths we can pass directly to the LLM or further refine to generate narratively rich responses. By prioritizing the “story” over pure topical alignment, we can influence LLMs to speak more like humans.ConclusionAs artificial intelligence becomes more integrated into our daily lives, the focus shifts from technical capability to emotional capacity. As base capability evolves, so must the pillars of our systems. By accounting for the semantic, emotional, and temporal components of events using the Affective Link Score and by following a branching, stream-like retrieval process for memories with Context Path Traversal, we can generate more human-like responses to emotional content.The source code for this can be found at https://github.com/jeje1197/AffectiveRAG.References1. Understanding the Effects of Trauma | Improving Lives Counseling Services. https://improvinglivescounseling.com/understanding-the-effects-of-trauma2. Evans, J. (2025). Affective RAG: Multi-Dimensional Recall with the Affective Link Score. Zenodo. https://doi.org/10.5281/zenodo.18327134Affective RAG: A Step Beyond Semantic Retrieval into Artificial Episodic Memory was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.