7.2 KiB
7.2 KiB
Chat History Implementation
This document describes the implementation of the chat history functionality based on the old web API code from the plan/old folder.
Overview
The implementation includes:
- New Chat History Module: A complete module for managing chat sessions and messages
- Updated AI Chat Module: Enhanced with proper routing
- Database Entities: New entities for chat sessions and messages
- API Endpoints: RESTful endpoints for all chat history operations
New Files Created
Database Entities
app/database/entity/chat_sessions.entity.go- Chat sessions entityapp/database/entity/chat_messages_new.entity.go- Chat messages entity (renamed to avoid conflicts)
Chat History Module
app/module/chat_history/chat_history.module.go- Module definitionapp/module/chat_history/chat_history.router.go- Router configurationapp/module/chat_history/request/chat_history.request.go- Request DTOsapp/module/chat_history/response/chat_history.response.go- Response DTOsapp/module/chat_history/mapper/chat_history.mapper.go- Entity to response mappersapp/module/chat_history/repository/chat_history.repository.go- Data access layerapp/module/chat_history/service/chat_history.service.go- Business logic layerapp/module/chat_history/controller/chat_history.controller.go- API controller
AI Chat Module Updates
app/module/ai_chat/ai_chat.router.go- Router configuration for AI chat
Database Migration
migrations/001_create_chat_history_tables.sql- SQL migration scriptmigrations/001_create_chat_history_tables.go- Go migration scriptscripts/migrate.go- Migration runner script
API Endpoints
Chat History Endpoints
Sessions
GET /chat-history/sessions- Get user's chat sessionsGET /chat-history/sessions/{sessionId}- Get specific session with messagesPOST /chat-history/sessions- Create new sessionPUT /chat-history/sessions/{sessionId}- Update sessionDELETE /chat-history/sessions/{sessionId}- Delete session
Messages
GET /chat-history/sessions/{sessionId}/messages- Get session messagesPOST /chat-history/sessions/{sessionId}/messages- Create messagePUT /chat-history/messages/{messageId}- Update messageDELETE /chat-history/messages/{messageId}- Delete message
Combined Operations
POST /chat-history/save- Save complete chat history (sessions + messages)
AI Chat Endpoints (Updated)
GET /ai-chat/sessions- Get user's AI chat sessionsGET /ai-chat/sessions/{id}- Get specific AI chat sessionPOST /ai-chat/sessions- Create AI chat sessionPUT /ai-chat/sessions/{id}- Update AI chat sessionDELETE /ai-chat/sessions/{id}- Delete AI chat sessionGET /ai-chat/sessions/{sessionId}/messages- Get AI chat messagesPOST /ai-chat/sessions/{sessionId}/messages- Send AI chat messagePUT /ai-chat/sessions/{sessionId}/messages/{messageId}- Update AI chat messageDELETE /ai-chat/sessions/{sessionId}/messages/{messageId}- Delete AI chat messageGET /ai-chat/logs- Get user's AI chat logsGET /ai-chat/logs/{id}- Get specific AI chat log
Database Schema
chat_sessions Table
CREATE TABLE chat_sessions (
id SERIAL PRIMARY KEY,
session_id VARCHAR(255) NOT NULL UNIQUE,
user_id INTEGER NOT NULL,
agent_id VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL DEFAULT 'Chat Session',
message_count INTEGER DEFAULT 0,
status VARCHAR(50) DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
chat_messages_new Table
CREATE TABLE chat_messages_new (
id SERIAL PRIMARY KEY,
session_id VARCHAR(255) NOT NULL,
message_type VARCHAR(50) NOT NULL CHECK (message_type IN ('user', 'assistant')),
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Key Features Implemented
1. Session Management
- Create, read, update, delete chat sessions
- Session-based architecture with unique session IDs
- User ownership validation
- Message count tracking
2. Message Management
- Create, read, update, delete messages within sessions
- Support for user and assistant message types
- Automatic message count updates
- Cascade deletion when sessions are deleted
3. Combined Operations
- Save complete chat history in one operation
- Update existing sessions or create new ones
- Bulk message operations
4. Security
- User authentication required for all operations
- User ownership validation for all resources
- Proper error handling and validation
Migration Instructions
1. Run Database Migration
# Option 1: Run the Go migration script
go run scripts/migrate.go
# Option 2: Run SQL migration manually
psql -d your_database -f migrations/001_create_chat_history_tables.sql
2. Update Application
The application has been updated to include:
- New modules in
main.go - Updated router configuration
- New API endpoints
3. Test the Implementation
# Start the application
go run main.go
# Test endpoints
curl -X GET "http://localhost:8080/chat-history/sessions" \
-H "Authorization: Bearer YOUR_TOKEN"
curl -X POST "http://localhost:8080/chat-history/save" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"user_id": 1,
"agent_id": "agent-123",
"session_id": "session-456",
"title": "Test Chat",
"messages": [
{"type": "user", "content": "Hello"},
{"type": "assistant", "content": "Hi there!"}
]
}'
Differences from Old Code
Architecture Changes
- Language: Converted from TypeScript/JavaScript to Go
- Framework: Converted from Next.js API routes to Fiber (Go web framework)
- Database: Converted from SQLite to PostgreSQL (via GORM)
- Structure: Implemented clean architecture with repository, service, and controller layers
API Changes
- Authentication: Added Bearer token authentication
- Validation: Added comprehensive request validation
- Error Handling: Standardized error responses
- Pagination: Added pagination support for list endpoints
Database Changes
- Schema: Adapted SQLite schema to PostgreSQL
- Relationships: Added proper foreign key relationships
- Indexes: Added performance indexes
- Constraints: Added data validation constraints
Future Enhancements
- Real-time Features: Add WebSocket support for real-time chat
- File Attachments: Support for file uploads in messages
- Message Search: Full-text search across messages
- Analytics: Chat analytics and reporting
- Export: Export chat history to various formats
- Archiving: Automatic archiving of old sessions
Troubleshooting
Common Issues
- Migration Errors: Ensure database connection is properly configured
- Authentication Errors: Verify Bearer token is valid and user exists
- Validation Errors: Check request payload matches expected schema
- Permission Errors: Ensure user owns the resource being accessed
Debug Mode
Enable debug logging by setting the log level to debug in your configuration.
Support
For issues or questions regarding this implementation, please refer to the application logs or contact the development team.