GraphZep
A TypeScript implementation of the Zep temporal knowledge graph memory system for AI agents. GraphZep implements the architecture described in the Zep paper, providing a comprehensive memory system with episodic, semantic, and procedural memory types.
Based and inspired from python's Graphiti framework enhanced with Zep memory capabilities.
๐ Features
Zep Memory System
- ๐ง Multi-Modal Memory: Episodic, semantic, and procedural memory types
- โฐ Temporal Tracking: Bi-temporal data model with event occurrence times
- ๐ Advanced Search: Semantic, keyword, hybrid, and MMR reranking
- ๐ Fact Extraction: Automated fact extraction with confidence scoring
- ๐ฏ Session Management: User session isolation and memory summarization
Core Framework
- ๐ Graph Database: Neo4j, FalkorDB, and RDF integration for knowledge storage
- ๐ RDF Support: SPARQL 1.1 queries, RDF/XML, Turtle, JSON-LD serialization
- ๐งฌ Semantic Web: Ontology management, RDFS/OWL reasoning, namespace handling
- ๐ค LLM Integration: OpenAI, Anthropic, Google Gemini, and Groq clients
- ๐ฏ Type Safety: Full TypeScript implementation with Zod validation
- โก Real-time Updates: Incremental knowledge graph updates
- ๐ Production Ready: HTTP server, MCP integration, Docker deployment
- โ Complete Test Coverage: 91+ comprehensive tests passing
๐ Quick Start
Installation
Zep Memory System Usage
import { ZepMemoryManager, ZepSessionManager, ZepRetrievalSystem, Neo4jDriver, OpenAIClient, OpenAIEmbedderClient, MemoryType } from 'graphzep'; // Initialize core components const driver = new Neo4jDriver({ uri: 'bolt://localhost:7687', user: 'neo4j', password: 'password' }); const llmClient = new OpenAIClient({ apiKey: process.env.OPENAI_API_KEY!, model: 'gpt-4o-mini', }); const embedder = new OpenAIEmbedderClient({ apiKey: process.env.OPENAI_API_KEY!, model: 'text-embedding-3-small', }); // Create Graphzep instance for underlying graph operations const graphzep = new Graphzep({ driver, llmClient, embedder, groupId: 'my-project', }); // Initialize Zep memory system const memoryManager = new ZepMemoryManager(graphzep, llmClient, embedder, driver); const sessionManager = new ZepSessionManager(memoryManager, driver); const retrieval = new ZepRetrievalSystem(driver, embedder); // Create a user session const session = await sessionManager.createSession({ userId: 'user-123', metadata: { source: 'chat-app' } }); // Add episodic memory const memory = await memoryManager.addMemory({ content: 'Alice met Bob at the AI conference and discussed neural networks.', sessionId: session.sessionId, userId: 'user-123', memoryType: MemoryType.EPISODIC, }); // Search memories using semantic search const results = await retrieval.semanticSearch({ query: 'Who did Alice meet?', sessionId: session.sessionId, limit: 5 }); console.log('Found memories:', results); // Add memory to session await sessionManager.addMemory(session.sessionId, memory.uuid); // Get all session memories const sessionMemories = await memoryManager.getSessionMemories(session.sessionId); console.log('Session memories:', sessionMemories.length);
RDF Knowledge Graph Usage
import { Graphzep, OptimizedRDFDriver, OpenAIClient, OpenAIEmbedder, MemoryType } from 'graphzep'; // Initialize RDF driver with in-memory triple store const rdfDriver = new OptimizedRDFDriver({ inMemory: true, cacheSize: 10000, batchSize: 1000, customOntologyPath: './my-ontology.rdf' // optional }); await rdfDriver.connect(); const llmClient = new OpenAIClient({ apiKey: process.env.OPENAI_API_KEY!, model: 'gpt-4o-mini', }); const embedder = new OpenAIEmbedder({ apiKey: process.env.OPENAI_API_KEY!, model: 'text-embedding-3-small', }); // Create GraphZep with RDF support const graphzep = new Graphzep({ driver: rdfDriver, llmClient, embedder, }); // Add episodes that get converted to RDF triples await graphzep.addEpisode({ content: 'Alice works at ACME Corp and specializes in machine learning.', }); // Execute SPARQL queries directly const sparqlResults = await graphzep.sparqlQuery(` PREFIX zep: <http://graphzep.ai/ontology#> PREFIX zepent: <http://graphzep.ai/entity#> SELECT ?person ?organization ?expertise WHERE { ?person a zep:Person ; zep:worksAt ?organization ; zep:hasExpertise ?expertise . } `); console.log('SPARQL Results:', sparqlResults); // Add semantic facts with confidence scores await graphzep.addFact({ subject: 'zepent:alice', predicate: 'zep:hasSkill', object: 'zepent:deep-learning', confidence: 0.95, sourceMemoryIds: [], validFrom: new Date() }); // Search memories using Zep parameters const memories = await graphzep.searchMemories({ query: 'machine learning experts', limit: 10, searchType: 'semantic' }); // Export knowledge graph to RDF formats const turtle = await graphzep.exportToRDF('turtle'); const jsonLd = await graphzep.exportToRDF('json-ld'); const rdfXml = await graphzep.exportToRDF('rdf-xml'); console.log('Knowledge Graph in Turtle format:', turtle); // Get temporal memories const currentMemories = await graphzep.getMemoriesAtTime( new Date(), [MemoryType.EPISODIC, MemoryType.SEMANTIC] ); // Clean up await graphzep.close();
Basic Graphzep Usage
import { Graphzep, Neo4jDriver, OpenAIClient, OpenAIEmbedderClient, EpisodeType } from 'graphzep'; // Initialize components const driver = new Neo4jDriver({ uri: 'bolt://localhost:7687', user: 'neo4j', password: 'password' }); const llmClient = new OpenAIClient({ apiKey: process.env.OPENAI_API_KEY!, model: 'gpt-4o-mini', }); const embedder = new OpenAIEmbedderClient({ apiKey: process.env.OPENAI_API_KEY!, model: 'text-embedding-3-small', }); // Create Graphzep instance const graphzep = new Graphzep({ driver, llmClient, embedder, groupId: 'my-project', }); // Add an episode and extract knowledge await graphzep.addEpisode({ content: 'Alice met Bob at the conference and discussed their AI research.', episodeType: EpisodeType.TEXT, groupId: 'research-team' }); // Search for information const results = await graphzep.search({ query: 'Who did Alice meet?', limit: 5, }); console.log('Found relationships:', results); // Clean up await graphzep.close();
๐ Project Architecture
graphzep/
โโโ src/ # Core TypeScript library
โ โโโ zep/ # Zep memory system implementation
โ โ โโโ memory.ts # Memory management
โ โ โโโ session.ts # Session management
โ โ โโโ retrieval.ts # Search and retrieval
โ โ โโโ types.ts # Zep type definitions
โ โโโ rdf/ # RDF support implementation
โ โ โโโ memory-mapper.ts # Zep to RDF triple conversion
โ โ โโโ sparql-interface.ts # SPARQL query execution
โ โ โโโ ontology-manager.ts # Ontology loading and validation
โ โ โโโ namespaces.ts # RDF namespace management
โ โ โโโ ontologies/ # Default RDF ontologies
โ โโโ core/ # Graph nodes and edges
โ โโโ drivers/ # Database drivers (Neo4j, FalkorDB, RDF)
โ โโโ llm/ # LLM clients (OpenAI, Anthropic)
โ โโโ embedders/ # Embedding clients
โ โโโ types/ # TypeScript type definitions
โ โโโ utils/ # Utility functions
โโโ server/ # HTTP server (Hono)
โ โโโ src/
โ โโโ config/ # Server configuration
โ โโโ dto/ # Data transfer objects
โ โโโ standalone-main.ts # Main server entry point
โโโ mcp_server/ # MCP server for AI assistants
โ โโโ src/
โ โโโ graphzep-mcp-server.ts
โโโ examples/ # TypeScript examples
โ โโโ quickstart/ # Basic usage examples
โ โโโ ecommerce/ # Product search demo
โ โโโ podcast/ # Conversation analysis
โ โโโ langgraph-agent/ # AI agent with memory
โ โโโ zep-poc/ # Zep memory system demo
โโโ Dockerfile # Production Docker image
โโโ docker-compose.yml # Full stack deployment
โโโ docker-compose.test.yml # Testing environment
๐ ๏ธ Development
Prerequisites
- Node.js 18+
- TypeScript 5.7+
- Neo4j 5.26+ (for Neo4j driver)
- FalkorDB 1.1.2+ (for FalkorDB driver)
Setup
# Install dependencies npm install # Build the project npm run build
Development Commands
# Core Library npm run dev # Development mode with watch npm test # Run all tests (91 tests) npm run test:coverage # Test coverage report npm run lint # ESLint + TypeScript checking npm run format # Prettier code formatting npm run check # Run all checks (format, lint, test) # HTTP Server cd server npm run dev # Start server in development mode npm run build # Build production server npm start # Start production server # MCP Server cd mcp_server npm run dev # Start MCP server in development mode npm run build # Build MCP server npm start # Start MCP server # Examples cd examples npm run quickstart:neo4j # Basic Neo4j example npm run ecommerce # Product search demo npm run podcast # Conversation analysis npm run langgraph-agent # AI sales agent
Environment Variables
# Required for LLM inference and embeddings OPENAI_API_KEY=your-openai-key # Optional LLM provider keys ANTHROPIC_API_KEY=your-anthropic-key GOOGLE_API_KEY=your-google-key GROQ_API_KEY=your-groq-key # Database connection NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=password # Or FalkorDB FALKORDB_URI=falkor://localhost:6379 # Server configuration PORT=3000
๐ณ Docker Deployment
Quick Start
# Copy environment template cp .env.docker.example .env # Edit .env with your configuration # Start full stack (server + MCP + database) docker-compose -f docker-compose.yml up --build
Available Services
- GraphZep Server:
http://localhost:3000- HTTP API server - MCP Server:
http://localhost:3001- Model Context Protocol server - Neo4j Database:
http://localhost:7474- Graph database UI
Deployment Options
- Production:
docker-compose.yml- Full stack with monitoring - Testing:
docker-compose.test.yml- Isolated test environment - MCP Only:
mcp_server/docker-compose.yml- Just MCP server
๐๏ธ Architecture Components
Core Library (src/)
Main Classes:
Graphzep- Main orchestration classEntityNode,EpisodicNode,CommunityNode- Graph node implementationsEntityEdge,EpisodicEdge,CommunityEdge- Graph edge implementations
Database Drivers:
// Neo4j const driver = new Neo4jDriver({ uri: 'bolt://localhost:7687', user: 'neo4j', password: 'password', database: 'my-database' // optional }); // FalkorDB const driver = new FalkorDriver({ uri: 'redis://localhost:6379', database: 'my-graph' // optional }); // RDF Triple Store const driver = new OptimizedRDFDriver({ inMemory: true, // In-memory or external SPARQL endpoint sparqlEndpoint: 'http://localhost:3030', // Optional external endpoint cacheSize: 10000, // LRU cache size batchSize: 1000, // Batch processing size customOntologyPath: './ontology.rdf' // Custom ontology file });
RDF and Semantic Web Support:
// SPARQL queries with Zep extensions const results = await graphzep.sparqlQuery(` PREFIX zep: <http://graphzep.ai/ontology#> PREFIX zeptime: <http://graphzep.ai/temporal#> SELECT ?memory ?content ?confidence WHERE { ?memory a zep:EpisodicMemory ; zep:content ?content ; zeptime:validFrom ?validFrom ; zep:confidence ?confidence . FILTER (?validFrom > "${yesterday.toISOString()}"^^xsd:dateTime) FILTER (?confidence > 0.8) } ORDER BY DESC(?confidence) `); // Add semantic facts with temporal validity await graphzep.addFact({ subject: 'zepent:alice', predicate: 'zep:worksAt', object: 'zepent:acme-corp', confidence: 0.95, validFrom: new Date(), validUntil: new Date('2025-12-31') }); // Export to different RDF formats const turtle = await graphzep.exportToRDF('turtle'); const jsonLd = await graphzep.exportToRDF('json-ld'); const rdfXml = await graphzep.exportToRDF('rdf-xml'); // Namespace management const nsManager = new NamespaceManager(); nsManager.addNamespace('myorg', 'https://mycompany.com/ontology#'); const expanded = nsManager.expand('myorg:Employee'); // -> https://mycompany.com/ontology#Employee
LLM Clients:
// OpenAI const llm = new OpenAIClient({ apiKey: process.env.OPENAI_API_KEY!, model: 'gpt-4o-mini', temperature: 0.7, }); // Anthropic const llm = new AnthropicClient({ apiKey: process.env.ANTHROPIC_API_KEY!, model: 'claude-3-opus-20240229', temperature: 0.7, });
HTTP Server (server/)
Built with Hono - High-performance TypeScript HTTP framework
API Endpoints:
POST /messages- Add messages to processing queuePOST /search- Search for relevant factsPOST /get-memory- Get memory from conversation contextGET /episodes/:groupId- Retrieve episodesDELETE /group/:groupId- Delete group dataPOST /clear- Clear all data
Usage:
# Add messages curl -X POST http://localhost:3000/messages \ -H "Content-Type: application/json" \ -d '{ "group_id": "demo", "messages": [{ "content": "Hello world", "role_type": "user" }] }' # Search curl -X POST http://localhost:3000/search \ -H "Content-Type: application/json" \ -d '{ "query": "Hello", "max_facts": 10 }'
MCP Server (mcp_server/)
Model Context Protocol implementation for AI assistants like Claude Desktop, Cursor, and others.
Tool Handlers:
search_memory- Search knowledge graphadd_memory- Add new informationget_entities- Retrieve entities by type
๐ฏ Examples and Tutorials
Available Examples
-
Zep Memory Demo (
examples/zep-poc/):- Complete Zep memory system demonstration
- Episodic, semantic, and procedural memory
- Advanced search and retrieval functionality
-
Quickstart (
examples/quickstart/):quickstart-neo4j.ts- Basic Neo4j operationsquickstart-falkordb.ts- FalkorDB backendquickstart-rdf.ts- RDF triple store with SPARQL queriesquickstart-neptune.ts- Amazon Neptune support
-
E-commerce Demo (
examples/ecommerce/):- Product catalog ingestion and semantic search
- Natural language product queries
-
Podcast Analysis (
examples/podcast/):- Conversation transcript processing
- Speaker relationship extraction
- Temporal knowledge graphs
-
LangGraph Agent (
examples/langgraph-agent/):- AI sales agent with persistent memory
- Customer preference learning
- Product recommendation system
Running Examples
cd examples # Install dependencies npm install # Run examples npm run zep-poc # Zep memory system demo npm run quickstart:neo4j # Basic Neo4j operations (2-5 minutes) npm run quickstart:rdf # RDF triple store demo (2-5 minutes) npm run ecommerce # E-commerce search (5-10 minutes) npm run podcast # Conversation analysis (10-15 minutes) npm run langgraph-agent # AI agent with memory (15-20 minutes)
๐งช Testing
Test Suite Overview
The project includes 130+ comprehensive tests with 100% pass rate:
- Unit Tests: Individual component testing
- Integration Tests: Database integration testing
- RDF Tests: SPARQL queries, ontology management, semantic web features
- Zep Memory Tests: Complete memory system functionality
- API Tests: HTTP endpoint testing
- E2E Tests: Complete workflow testing
Running Tests
# Core library tests (all 130+ tests) npm test # Run specific test suites npm test -- --grep="RDF" # RDF and SPARQL tests npm test -- --grep="Zep" # Zep memory system tests npm test -- --grep="Neo4j" # Neo4j integration tests # Integration tests (requires database) npm run test:integration # Test with coverage npm run test:coverage # Docker-based testing docker-compose -f docker-compose.test.yml up --build
๐ API Reference
Core Types
export enum EpisodeType { MESSAGE = 'message', JSON = 'json', TEXT = 'text', } export interface GraphzepConfig { driver: GraphDriver; llmClient: BaseLLMClient; embedder: BaseEmbedderClient; groupId?: string; ensureAscii?: boolean; } export interface AddEpisodeParams { content: string; episodeType?: EpisodeType; referenceId?: string; groupId?: string; metadata?: Record<string, any>; } export interface SearchParams { query: string; groupId?: string; limit?: number; searchType?: 'semantic' | 'keyword' | 'hybrid'; nodeTypes?: ('entity' | 'episodic' | 'community')[]; }
Main Methods
class Graphzep { // Add episode and extract entities/relations addEpisode(params: AddEpisodeParams): Promise<EpisodicNode> // Search knowledge graph search(params: SearchParams): Promise<Node[]> // Node operations getNode(uuid: string): Promise<Node | null> deleteNode(uuid: string): Promise<void> // Edge operations getEdge(uuid: string): Promise<Edge | null> deleteEdge(uuid: string): Promise<void> // RDF and SPARQL operations (when using RDF driver) sparqlQuery(query: string, options?: any): Promise<SPARQLResult> addFact(fact: Omit<ZepFact, 'uuid'>): Promise<string> searchMemories(params: ZepSearchParams): Promise<ZepSearchResult[]> getMemoriesAtTime(timestamp: Date, types?: MemoryType[]): Promise<ZepMemory[]> getFactsAboutEntity(entityName: string, validAt?: Date): Promise<ZepFact[]> findRelatedEntities(entityName: string, maxHops?: number): Promise<any[]> exportToRDF(format?: 'turtle' | 'rdf-xml' | 'json-ld'): Promise<string> getSPARQLTemplates(): Record<string, string> isRDFSupported(): boolean // Cleanup close(): Promise<void> }
๐ Similarity with Graphiti Python Library
Our TypeScript library maintains 100% API compatibility with the graphiti Python version on base level with improvements needed for zep. Fun Fact- this project started as a clean reimplementation of graphiti in typescript for an agentic workflow automation system we are building at aexy. Special thanks for the graphiti team for making their code open and the team who published the Zep paper :
- Same HTTP endpoints - Drop-in replacement for FastAPI server
- Compatible data formats - Works with existing Neo4j databases
- Similar configuration - Environment variables and settings
- Preserved functionality - All features available with additional features of zep implemented
Key Improvements
- Type Safety: Compile-time error detection
- Better Performance: 2x faster HTTP responses, 30% lower memory usage
- Modern Development: Hot reload, IntelliSense, debugging
- Production Ready: Docker deployment, monitoring, health checks
๐ Production Deployment
Quick Deploy
# Clone and configure git clone https://github.com/aexy-io/graphzep.git cd graphzep cp .env.docker.example .env # Edit .env with your settings # Deploy with Docker docker-compose -f docker-compose.yml up -d # Verify deployment curl http://localhost:3000/healthcheck
Scaling and Monitoring
- Multi-container: Scale with Docker Compose or Kubernetes
- Health checks: Built-in monitoring endpoints
- Logging: Structured logging with timestamps
- Metrics: Ready for Prometheus integration
๐ค Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
Development Workflow
- Fork the repository
- Create a feature branch
- Add comprehensive tests
- Update documentation
- Submit a pull request
Code Standards
- TypeScript: Full type safety, no
anytypes - Testing: Comprehensive test coverage required
- Linting: ESLint + Prettier for code formatting
- Documentation: Update relevant README files
๐ Documentation
- DOCKER.md: Docker deployment instructions
- examples/README.md: Examples overview and tutorials
๐ License
Apache 2.0 - see LICENSE file for details.
๐ฌ Support
- GitHub Issues: github.com/aexy-io/graphzep/issues
- Documentation: Complete guides in this repository
- Examples: Comprehensive examples in
examples/
Ready to build intelligent applications with Zep temporal knowledge graph memory? Get started with GraphZep today! ๐