DEV Community

Cover image for Open Source Project of the Day (#119): Cognee — Persistent Cross-Session Memory for AI Agents
WonderLab
WonderLab

Posted on

Open Source Project of the Day (#119): Cognee — Persistent Cross-Session Memory for AI Agents

Introduction

"Every new AI agent session starts with amnesia. The architecture decision from yesterday, the technical choice made last week, the pitfall from three months ago — the agent knows none of it when a new session opens."

This is article #119 in the Open Source Project of the Day series. Today's project is Cognee — an open-source AI agent memory platform that gives agents a persistent memory layer across sessions.

Using Claude Code on a project spanning several weeks reveals a recurring cost: every new session requires re-briefing context. What's the design decision behind this module, why was approach A chosen over B last time, how does the current task connect to the overall goals. That background doesn't just waste tokens — worse, the agent might make choices that contradict previous decisions without knowing it.

Cognee's positioning is memory infrastructure: context generated during agent sessions gets structured into a knowledge graph, queryable and referenceable in later sessions. Cross-session continuity shifts from "user manually explains context" to "auto-retrieved from memory store."

What You'll Learn

  • Why Cognee's memory design goes further than standard RAG: the cognitive science foundation
  • The four core operations: remember / recall / forget / improve
  • Two-layer design: session memory vs. permanent graph memory
  • Auto-routing search: how it automatically selects the optimal retrieval strategy
  • The single-Postgres architecture that covers the entire memory stack
  • BEAM benchmark results
  • Claude Code plugin and MCP integration

Prerequisites

  • Familiarity with AI agent basics
  • Basic understanding of vector databases and knowledge graphs
  • Python experience

Project Background

What Is Cognee?

Cognee is an open-source AI agent memory platform that integrates vector embeddings, graph reasoning, and ontology generation into a unified memory infrastructure.

Its paper title — "Optimizing the Interface Between Knowledge Graphs and LLMs for Complex Reasoning" — describes the design direction precisely: not simply storing documents for vector retrieval, but building a better interface between LLMs and knowledge graphs to enable complex reasoning.

Author / Team

  • Organization: Topoteretes UG (Germany)
  • Paper: arXiv:2505.24478 (Markovic et al., 2025)
  • Website: cognee.ai
  • License: Apache-2.0

Project Stats

  • ⭐ GitHub Stars: 27,400+
  • 🍴 Forks: 2,600+
  • 📦 Releases: 125
  • 🔁 SDK runs/month: 5M+
  • 📄 License: Apache-2.0

Core Design: Memory Is Not Just RAG

Before the API, the design philosophy.

Why Not Just RAG

Standard RAG logic: document → embed → store in vector database → retrieve semantically similar chunks at query time → return relevant text.

This approach has two fundamental limitations:

  1. Relationships are invisible: Vector similarity finds semantically close text but can't find logically related entities. "Alice manages Bob; Bob owns the authentication module" — asking "who is the decision-maker for the auth module?" requires connecting two pieces of information that aren't directly similar to each other in vector space.

  2. Time dimension is absent: All text chunks are treated equally, with no notion of "this decision was made two months ago and later reversed."

Cognee supplements vector retrieval with a knowledge graph: entities and relationships are explicitly modeled, making multi-hop reasoning possible.

Cognitive Science Foundation

Cognee's design references cognitive science's memory taxonomy:

  • Episodic memory: Memories of specific events with timestamps ("Last Wednesday we discussed the auth approach")
  • Semantic memory: Factual knowledge ("JWT is an authentication mechanism")
  • Working memory: The active context of the current session

Cognee's session memory corresponds to working memory (fast read/write, non-persistent). The permanent graph corresponds to episodic and semantic memory (persistent, queryable across sessions).


Four Core Operations

import cognee, asyncio

async def main():
    # 1. Remember: store information in memory
    await cognee.remember("The auth module decided to use JWT, reasoning was...")

    # 2. Recall: retrieve relevant memories
    results = await cognee.recall("What are the technical decisions for the auth module?")
    for result in results:
        print(result)

    # 3. Forget: remove a dataset from memory
    await cognee.forget(dataset="draft_decisions")

    # 4. Improve: refine the knowledge graph structure
    await cognee.improve()

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

cognee.remember(source)

Accepts multiple input formats:

# Text string
await cognee.remember("Alice is Bob's technical lead, responsible for backend architecture decisions")

# Document file
await cognee.remember("path/to/architecture_decision.md")

# URL (web page content)
await cognee.remember("https://docs.company.com/decisions/auth-module")

# Structured data
await cognee.remember({"decision": "JWT", "date": "2026-06-01", "owner": "Alice"})
Enter fullscreen mode Exit fullscreen mode

remember triggers the ECL pipeline:

  • Extract: Identify entities from raw content (people, concepts, technologies, dates)
  • Cognify: Build relationships between entities, generate ontology structure
  • Load: Write to graph database and vector index

cognee.recall(query)

Auto-routing retrieval — no need to specify which retrieval strategy. Cognee analyzes the query type and selects automatically:

# Factual question → graph precise query
results = await cognee.recall("Who owns the auth module?")
# → Direct graph query: (auth module) -[owner]-> (?)

# Semantic search → vector similarity
results = await cognee.recall("Discussions related to OAuth")
# → Vector retrieval for "OAuth" related text

# Complex reasoning → hybrid retrieval
results = await cognee.recall("How do the architecture decisions from 3 months ago affect the current auth approach?")
# → Graph temporal traversal + vector semantic matching + result fusion
Enter fullscreen mode Exit fullscreen mode

cognee.forget(dataset) and cognee.improve()

forget supports fine-grained deletion: removes only a specific dataset's memories without affecting others.

improve triggers graph optimization: merges duplicate entities, updates stale relationships, removes low-confidence nodes.


Two-Layer Memory Architecture

New session starts
    ↓
Working memory (session memory)
    ├── Fast read/write (Redis or Postgres session cache)
    ├── Stores current session context
    └── Async sync to permanent graph at session end

Permanent graph memory
    ├── Knowledge graph (entities + relationships)
    ├── Vector index (semantic similarity)
    └── Persistent across sessions, queryable by all agents
Enter fullscreen mode Exit fullscreen mode

The practical meaning:

  • High-frequency reads/writes within a session bypass the graph database (avoiding latency)
  • At session end, important session content flows into the permanent graph
  • On the next session launch, recall can find relevant memories from all previous sessions

Storage Backends

Cognee's most attractive deployment option is a single Postgres instance covering the entire memory stack:

Traditional agent memory requires:
  Neo4j (graph database)
  + Pinecone/Qdrant (vector database)
  + Redis (session cache)
  + PostgreSQL (business data)
  = 4 separate services to maintain

Cognee on Postgres:
  PostgreSQL + pgvector + Apache AGE (graph extension)
  = 1 service handles everything
Enter fullscreen mode Exit fullscreen mode

Full supported backends:

Role Options
Graph database Postgres (default), Neo4j, Neptune, Kuzudb
Vector database pgvector, LanceDB, Qdrant, ChromaDB, Weaviate, Milvus
Relational database Postgres, SQLite (local dev)
Session cache Postgres, Redis

Installation and Quick Start

# Basic install
uv pip install cognee

# With Postgres backend (production recommended)
pip install "cognee[postgres]"
Enter fullscreen mode Exit fullscreen mode

Local development (SQLite):

import cognee, asyncio, os

os.environ["LLM_API_KEY"] = "your_openai_key"

async def main():
    await cognee.remember("Alice owns the auth module, decided to use JWT after evaluating OAuth but dropped it for implementation complexity")
    await cognee.remember("Bob owns the database layer, using PostgreSQL, currently evaluating whether to shard")

    results = await cognee.recall("Technical decisions related to authentication")
    for r in results:
        print(r)

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Postgres production config:

import cognee

cognee.config.set_databases(
    db_url="postgresql://user:pass@localhost:5432/cognee",
    vector_db="pgvector",
    graph_db="postgres",
)
Enter fullscreen mode Exit fullscreen mode

Claude Code Integration

Two integration modes:

MCP Server

# Start MCP server via Docker
docker run -p 8765:8765 cognee/cognee-mcp

# Configure for Claude Code
# ~/.claude/mcp.json
{
  "mcpServers": {
    "cognee": {
      "command": "docker",
      "args": ["run", "-p", "8765:8765", "cognee/cognee-mcp"],
      "transport": "http",
      "url": "http://localhost:8765"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Available MCP tools: store memory, retrieve memory, search graph.

Claude Code Plugin (Session Lifecycle Hooks)

Deeper integration:

Session starts
    → Inject relevant historical memories into system prompt

Session active
    → Track tool calls (bash, read, write, etc.)
    → Track agent reasoning process

Session ends
    → Sync key session information to permanent graph
    → Extract decisions, constraints, learned facts
Enter fullscreen mode Exit fullscreen mode

Benchmark Results

BEAM (Boundary Evaluation of Agents and Models) is a benchmark specifically measuring long-context memory capability:

Context Scale Cognee Prior Best RAG Baseline
100K tokens 0.79 0.735 ~0.33
10M tokens 0.67 0.641 ~0.33

Two key data points:

  1. The graph + vector hybrid approach significantly outperforms the pure RAG baseline on long context (0.79 vs. 0.33)
  2. Performance remains stable at extreme 10M token context (0.67), where RAG baselines become essentially non-functional

Multi-Language SDKs

Language Package Use Case
Python cognee Primary SDK
Rust cognee-rs High-performance embedded scenarios
TypeScript @cognee/cognee-ts Node.js / frontend integration
CLI cognee-cli Command-line operations + local Web UI

Links and Resources


Conclusion

Cognee's core contribution is shifting the memory problem from "re-feed context to every session" to "retrieve relevant memories from a persistent graph."

The BEAM benchmark results validate the technical approach: pure RAG effectively fails on long-context scenarios, while graph-based relationship modeling enables multi-hop reasoning. Auto-routing search hides the underlying complexity — users don't need to manually choose retrieval strategies.

The single-Postgres deployment option lowers the production adoption barrier. You don't need to simultaneously maintain Neo4j, Redis, a vector database, and a relational database.

27.4k Stars, 5M+ monthly SDK invocations, production deployments at Bayer and other enterprises — this isn't an experimental project. For teams building AI agent systems that need cross-session memory, Cognee is one of the most complete open-source options available.


Explore PrimeSkills — A marketplace for handpicked AI Agents and skills. Each is validated in real enterprise workflows, stripping away hype and keeping only what truly works.

Welcome to my Homepage for more useful insights and interesting products.

Top comments (0)