Skip to content

shariarfaisal/chatvault

Repository files navigation

ChatVault

ChatVault is an enterprise-grade, lightweight conversation persistence layer specifically designed for AI-powered chat applications and conversational interfaces. Built with a zero-dependency philosophy using pure Go and SQLite, it provides a robust, scalable solution for storing, managing, and retrieving AI-generated conversations and multi-turn dialogues.

Why ChatVault?

ChatVault serves as a dedicated backend infrastructure for AI chat applications, offering persistent storage for conversation histories, context management, and message threading. It bridges the gap between ephemeral AI interactions and long-term conversation retention, enabling applications to maintain context across sessions, analyze conversation patterns, and provide seamless user experiences in AI-driven communication platforms.

Key Features

AI-First Architecture

  • 🤖 Purpose-Built for AI - Native support for AI conversation patterns (user, assistant, system, tool roles)
  • 🔄 Multiple Content Types - Text, JSON, Markdown, Code, Tool Use, and mixed media support
  • 📊 Conversation Analytics - Built-in metrics for AI interaction analysis

Technical Excellence

  • 🚀 Zero External Dependencies - Pure Go with SQLite for maximum portability
  • High Performance - Sub-millisecond response times with SQLite WAL mode
  • 🔒 Multi-Tenant by Design - Complete user data isolation for SaaS applications
  • 📝 Flexible Metadata - JSON support for custom session and message attributes
  • 🌐 RESTful API - Clean, intuitive endpoints with comprehensive documentation
  • 📦 Professional SDK - JavaScript/TypeScript SDK with full type definitions

Quick Start

Prerequisites

  • Go 1.21 or higher
  • SQLite3

Installation

# Clone the repository
git clone https://github.com/chatvault/chatvault.git
cd chatvault

# Install dependencies
make install

# Setup database
make setup

# Run the server
make run

The server will start on http://localhost:7734

Using Docker

# Build the Docker image
make docker-build

# Run the container
make docker-run

API Usage

Authentication

Include your user ID in requests using one of these methods:

  • Header: X-User-ID: user_123
  • Query parameter: ?user_id=user_123
  • Bearer token: Authorization: Bearer user_123

Basic Example

# Create a session
curl -X POST http://localhost:7734/sessions \
  -H "X-User-ID: user_123" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "chat",
    "title": "My Chat Session"
  }'

# Add a message
curl -X POST http://localhost:7734/messages \
  -H "X-User-ID: user_123" \
  -H "Content-Type: application/json" \
  -d '{
    "session_id": "session_abc123",
    "role": "user",
    "content": {"type": "text", "text": "Hello!"}
  }'

# Get session with messages
curl -X GET "http://localhost:7734/sessions/session_abc123?include_messages=true" \
  -H "X-User-ID: user_123"

JavaScript SDK

Installation

npm install @chatvault/sdk

Usage

import ChatVault from '@chatvault/sdk';

// Initialize
const vault = new ChatVault({
  baseURL: 'http://localhost:7734',
  userId: 'user_123'
});

// Create a session
const session = await vault.sessions.create({
  type: 'chat',
  title: 'Customer Support'
});

// Add messages
await vault.messages.create({
  sessionId: session.id,
  role: 'user',
  content: { type: 'text', text: 'I need help!' }
});

// Get full session
const fullSession = await vault.sessions.get(session.id);
console.log(fullSession.messages);

API Endpoints

Sessions

Method Endpoint Description
POST /sessions Create a new session
GET /sessions/:id Get session by ID
GET /sessions List user's sessions
PUT /sessions/:id Update session
DELETE /sessions/:id Delete session

Messages

Method Endpoint Description
POST /messages Create a message
GET /messages/:id Get message by ID
GET /sessions/:id/messages List session messages
PUT /messages/:id Update message
DELETE /messages/:id Delete message

Analytics

Method Endpoint Description
GET /users/:user_id/stats Get user statistics
GET /export?format=json Export user data

Configuration

Environment Variables

# Database
CHATVAULT_DB_PATH=./data/chat.db
CHATVAULT_DB_MAX_CONNECTIONS=25

# Server
CHATVAULT_PORT=7734
CHATVAULT_MAX_REQUEST_SIZE=10485760  # 10MB
CHATVAULT_TIMEOUT=30s

# Rate Limiting
CHATVAULT_RATE_LIMIT=100  # per minute per user
CHATVAULT_RATE_LIMIT_ENABLED=true

# CORS
CHATVAULT_CORS_ORIGINS=*
CHATVAULT_CORS_METHODS=GET,POST,PUT,DELETE,OPTIONS

Development

Project Structure

chatvault/
├── cmd/chatvault/       # Main application entry
├── internal/
│   ├── api/            # HTTP handlers and server
│   ├── config/         # Configuration management
│   ├── models/         # Data models
│   ├── service/        # Business logic
│   └── storage/        # Database layer
├── data/               # SQLite database files
└── tests/              # Test files

Available Make Commands

make help          # Show all available commands
make build         # Build the binary
make test          # Run tests
make lint          # Run linters
make fmt           # Format code
make clean         # Clean build artifacts
make migrate       # Run database migrations
make seed          # Seed sample data
make dev           # Run with auto-reload (requires air)

Running Tests

# Run all tests
make test

# Run with coverage
make test-coverage

# Run benchmarks
make benchmark

Content Types

ChatVault supports various content types for messages:

Text

{
  "type": "text",
  "text": "Simple text message"
}

Mixed Content

{
  "type": "mixed",
  "parts": [
    {"type": "text", "text": "Analysis results:"},
    {"type": "code", "language": "python", "code": "print('hello')"},
    {"type": "json", "data": {"result": "success"}}
  ]
}

Tool Use

{
  "type": "tool_use",
  "tool_name": "calculator",
  "tool_input": {"expression": "2+2"},
  "tool_output": {"result": 4}
}

Security

  • User Isolation: All data is strictly isolated by user ID
  • SQL Injection Prevention: Uses parameterized queries
  • Rate Limiting: Configurable per-user rate limits
  • CORS Support: Configurable CORS policies
  • Request Size Limits: Prevents abuse with configurable limits

Performance

  • SQLite WAL Mode: Better concurrency with Write-Ahead Logging
  • Connection Pooling: Configurable connection limits
  • Indexed Queries: Optimized database indexes
  • Efficient JSON: Native JSON support in SQLite
  • Pagination: All list endpoints support pagination

Use Cases

ChatVault is ideal for:

  • 💬 AI Chatbot Platforms - Store and manage conversation histories
  • 🎓 Educational AI Tutors - Track learning progress across sessions
  • 🏢 Customer Support Systems - Maintain context for AI-powered support agents
  • 📚 Documentation Assistants - Persist Q&A interactions with AI helpers
  • 📈 Conversational Analytics - Analyze AI interaction patterns and metrics
  • 🔧 Development Tools - Debug and review AI conversation flows

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT License - see LICENSE file for details

Support

Acknowledgments

Built with ❤️ using:

About

Lightweight conversation persistence layer for AI chat applications. Zero-dependency Go + SQLite backend with user isolation, analytics & TypeScript SDK

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors