Graph memory

Graph memory stores knowledge as entities connected by relationships. Unlike flat memory, it enables multi-hop reasoning. For example, "Who is the CEO of the company that made the iPhone?" requires traversing: iPhone → Apple → Tim Cook.

Knowledge graph example

Vector databases excel at similarity search ("find documents like this"). Knowledge graphs excel at relationship traversal ("who is connected to whom and how"). Use graphs when your queries require multi-hop reasoning across entities.

patterns/41_graph_memory.py
python
class GraphMemory:
    def __init__(self):
        self.entities = {}
        self.relationships = []

    def add_entity(self, name, entity_type, properties=None):
        self.entities[name] = {
            "type": entity_type, "properties": properties or {}
        }

    def add_relationship(self, source, relationship, target):
        self.relationships.append({
            "source": source, "relationship": relationship, "target": target
        })

    def find_path(self, source, target, max_depth=3):
        """Multi-hop traversal using DFS."""
        visited = set()
        paths = []
        def dfs(current, path, depth):
            if depth > max_depth or current in visited:
                return
            visited.add(current)
            if current == target:
                paths.append(list(path))
                return
            for rel in self.relationships:
                if rel["source"] == current:
                    path.append(rel)
                    dfs(rel["target"], path, depth + 1)
                    path.pop()
        dfs(source, [], 0)
        return paths

GraphMemory with entities, relationships, and multi-hop path finding.

Quiz: Quiz

Loading practice…

Flashcards: Flashcards

Loading practice…

Graph memory gives agents the ability to reason across relationships, not just retrieving facts but connecting the dots between them. That wraps up frontier reasoning patterns.