A dynamic knowledge graph system that learns from conversations in real-time. As users chat with the AI, their conversations are automatically indexed into both a vector database and a personalized knowledge graph, enabling context-aware responses without sending entire chat histories.
- Session-Based Knowledge Graphs: Each conversation/session has its own isolated knowledge graph
- Smart Context Management: Maintains only 3 most recent messages + retrieval-based context
- Async Graph Building: Background processing with queue management to prevent race conditions
- Hybrid Retrieval: Combines sliding window + vector search + graph traversal
- Real-time Learning: Captures topics, entities, and relationships from each conversation
-
Agent System (
agent/)- Conversational AI agent with memory tools
- User-specific context management
- Hybrid retrieval strategy
-
Storage Layer (
storage/)- PostgreSQL for vector storage and conversation history
- Neo4j for personalized knowledge graphs
- Async queue for graph updates
-
API Layer (
api/)- FastAPI with streaming responses
- Session management
- Background task handling
User Message → Agent Processing → Response
↓
[Async Queue]
↓
Vector DB + Knowledge Graph
↓
[Background Worker]
Message Flow:
- User sends a message
- System retrieves context using:
- Last 3 messages (sliding window)
- Relevant past conversations (vector search)
- User preferences & topics (knowledge graph)
- Agent generates response
- Message pair queued for async processing
- Background worker updates vector DB and knowledge graph
- Queue ensures no race conditions
Knowledge Graph Structure:
- Topic Nodes: Discussion subjects and themes
- Entity Nodes: People, places, concepts mentioned
- Relationship Edges: How topics and entities relate
- Episode Nodes: Conversation turns with timestamps
- Each session maintains its own isolated graph
- Python 3.11+
- PostgreSQL with pgvector extension
- Neo4j database
- LLM API key (OpenAI, Ollama, etc.)
python -m venv venv
.\venv\Scripts\activate # Windows
source venv/bin/activate # Linux/macOSpip install -r requirements.txtExecute the SQL schema:
psql -d $DATABASE_URL -f sql/schema.sqlCreate .env file:
# Database
DATABASE_URL=postgresql://user:password@host:port/dbname
# Neo4j
NEO4J_URI=bolt://localhost:7687
NEO4J_USER=neo4j
NEO4J_PASSWORD=your_password
# LLM Provider
LLM_PROVIDER=openai
LLM_BASE_URL=https://api.openai.com/v1
LLM_API_KEY=sk-your-key
LLM_CHOICE=gpt-4.1-mini
# Embeddings
EMBEDDING_PROVIDER=openai
EMBEDDING_BASE_URL=https://api.openai.com/v1
EMBEDDING_API_KEY=sk-your-key
EMBEDDING_MODEL=text-embedding-3-small
# Application
APP_PORT=8059
LOG_LEVEL=INFOpython -m api.mainpython cli.pyTo visualize the knowledge graph for a specific session or user:
# Visualize a specific conversation/session
python visualize_graph.py --conversation conv_user123_abc123
# Visualize all conversations for a user
python visualize_graph.py --user user123
# Visualize entire graph (all sessions)
python visualize_graph.py --limit 200
# Show detailed statistics
python visualize_graph.py --stats
# Advanced options
python visualize_graph.py --conversation conv_xyz --type interactive --output session_graphThis creates two files:
knowledge_graph.png- Static image of the graphknowledge_graph.html- Interactive visualization (open in browser!)
The interactive HTML version allows you to:
- 🖱️ Click and drag nodes to explore
- 🔍 Hover over nodes to see details
- 🎯 Zoom in/out and pan around
- 📊 See all entities and relationships
You can also access graph data via the API:
# Get graph data for a specific conversation
curl "http://localhost:8059/graph/data?conversation_id=conv_xyz&limit=100"
# Get graph statistics for a conversation
curl "http://localhost:8059/graph/stats?conversation_id=conv_xyz"
# Get all graphs for a user
curl "http://localhost:8059/graph/data?user_id=user123&limit=200"You: I'm interested in learning about Python programming
🤖 Assistant: Great! Python is an excellent programming language to learn.
What specifically about Python would you like to focus on? Web development,
data science, automation, or general programming concepts?
You: I think data science sounds interesting
🤖 Assistant: Perfect! Since you mentioned data science, I can help you get started.
The main libraries you'll want to learn are NumPy, Pandas, and Matplotlib...
[Type "new" to start a new session with a fresh knowledge graph]
You: new
✓ Started new conversation
You: What programming topics should I explore?
🤖 Assistant: There are many exciting areas in programming! What are your
interests or goals? Are you looking to build web applications, work with data,
create games, or something else?
Notice: Each session maintains its own isolated knowledge graph. Starting a new conversation creates a fresh context!
┌─────────────┐
│ User Message│
└──────┬──────┘
│
├──────────────────┐
│ │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Retrieve │ │ Store in │
│ Context │ │ Vector DB │
└──────┬───────┘ └──────────────┘
│
│ ┌────────────────┐
├─┤ Sliding Window │
│ └────────────────┘
│ ┌────────────────┐
├─┤ Vector Search │
│ └────────────────┘
│ ┌────────────────┐
└─┤ Graph Context │
└────────┬───────┘
│
▼
┌────────────────┐
│ Agent Response │
└────────┬───────┘
│
▼
┌────────────────┐
│ Async Queue │
│ (No blocking!) │
└────────┬───────┘
│
▼
┌────────────────┐
│ Background │
│ Worker Updates │
│ Knowledge Graph│
└────────────────┘
The system uses an async queue to prevent race conditions:
- User sends message → Agent responds immediately
- Response queued → Added to background processing queue
- Sequential processing → Queue worker processes updates one at a time
- Even if user sends next message → It won't interfere with graph building
- Queue ensures order → Messages processed in the order they were sent
For each user message, the system retrieves:
- Sliding Window (3 messages): Immediate context from current conversation
- Vector Search (Top 5): Similar past conversations across all sessions
- Knowledge Graph: User preferences, topics, and relationships
This hybrid approach provides both immediate and historical context without sending entire chat histories to the LLM.
Each conversation has its own isolated knowledge graph:
- Complete Isolation: Knowledge from one session doesn't leak into another
- Clean Context: Each conversation maintains its own coherent knowledge base
- Privacy: Different topics/projects can have completely separate contexts
- Easy Management: Close or archive individual session graphs when conversations end
See SESSION_ARCHITECTURE.md for detailed architecture documentation.
Instead of sending entire chat histories:
- Only 3 most recent messages sent directly
- Historical context retrieved via similarity search
- Knowledge graph provides learned facts and preferences
- Reduces token usage while maintaining context
The graph building happens in the background:
- API responds immediately (no waiting for graph updates)
- Messages queued for processing
- Background worker processes sequentially
- No race conditions between rapid messages
- User can continue chatting while graph updates
From each conversation turn, Graphiti extracts:
- Entities: Topics discussed, concepts mentioned
- Relationships: How topics relate to each other
- User Preferences: User likes, interests, goals
- Conversation Flow: How discussions evolve
- Temporal Facts: Information with timestamps
PostgreSQL with pgvector:
psql -d your_database < sql/schema.sqlNeo4j:
- Install Neo4j Desktop or use cloud instance
- Start database and note credentials
Copy .env.example to .env and fill in:
cp .env.example .env
# Edit .env with your credentialspip install -r requirements.txtpython -m api.mainIn a separate terminal:
python cli.py --user your_usernameNon-streaming chat endpoint.
Request:
{
"message": "Tell me about machine learning",
"user_id": "user123",
"conversation_id": "optional_conversation_id",
"metadata": {}
}Response:
{
"message": "Machine learning is...",
"conversation_id": "conv_user123_abc123",
"user_id": "user123",
"sources_used": ["sliding_window", "vector_search", "knowledge_graph"],
"metadata": {"queue_size": 2}
}Streaming chat endpoint with Server-Sent Events.
Events:
conversation: Conversation IDtext: Response text chunksend: End of response with queue sizeerror: Error message
Health check endpoint.
Response:
{
"status": "healthy",
"database": true,
"graph_database": true,
"llm_connection": true,
"queue_size": 3,
"version": "1.0.0",
"timestamp": "2025-11-30T..."
}Environment variables for customization:
# Context Management
SLIDING_WINDOW_SIZE=3 # Number of recent messages to include
MAX_RETRIEVAL_RESULTS=5 # Max vector search results
ENABLE_GRAPH_CONTEXT=true # Enable knowledge graph context
# Background Processing
GRAPH_UPDATE_DELAY=0.5 # Delay between graph updates (seconds)
MAX_QUEUE_SIZE=100 # Maximum queue size
# LLM Configuration
LLM_CHOICE=gpt-4.1-mini # Fast model for responses
EMBEDDING_MODEL=text-embedding-3-small # Efficient embeddingsIf the queue size keeps growing:
- Check Neo4j connection
- Verify LLM API is responding
- Consider using a faster/smaller model
- Increase
GRAPH_UPDATE_DELAY
If the agent doesn't remember previous conversations:
- Check that embeddings are being generated
- Verify vector search is returning results
- Check knowledge graph is being updated (see queue)
If responses are taking too long:
- Reduce
MAX_RETRIEVAL_RESULTS - Use a faster LLM model
- Check database connection latency
conversational-knowledge-graph/
├── agent/ # AI agent and prompts
│ ├── agent.py # Context retrieval and agent execution
│ └── prompts.py # System prompts
├── api/ # FastAPI application
│ └── main.py # API endpoints and streaming
├── storage/ # Data layer
│ ├── db_utils.py # PostgreSQL operations
│ ├── graph_utils.py # Neo4j/Graphiti operations
│ └── queue_manager.py # Async queue for graph updates
├── sql/ # Database schema
├── models.py # Pydantic models
├── providers.py # LLM provider configuration
├── cli.py # Command-line interface
└── README.md # This file
# Test database connection
python -c "from storage.db_utils import test_connection; import asyncio; print(asyncio.run(test_connection()))"
# Test API health
curl http://localhost:8059/health
# Test chat endpoint
curl -X POST http://localhost:8059/chat \
-H "Content-Type: application/json" \
-d '{"message": "Hello", "user_id": "test_user"}'- Add user preference extraction
- Implement topic clustering
- Add conversation summaries
- Multi-modal support (images, files)
- Export/import user knowledge graphs
- Analytics dashboard
- Multi-language support
MIT License - Feel free to use and modify!
Built with ❤️ using Pydantic AI, PostgreSQL, Neo4j, and Graphiti.