narasiahli-be/CHAT_HISTORY_IMPLEMENTATION.md

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:

  1. New Chat History Module: A complete module for managing chat sessions and messages
  2. Updated AI Chat Module: Enhanced with proper routing
  3. Database Entities: New entities for chat sessions and messages
  4. API Endpoints: RESTful endpoints for all chat history operations

New Files Created

Database Entities

  • app/database/entity/chat_sessions.entity.go - Chat sessions entity
  • app/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 definition
  • app/module/chat_history/chat_history.router.go - Router configuration
  • app/module/chat_history/request/chat_history.request.go - Request DTOs
  • app/module/chat_history/response/chat_history.response.go - Response DTOs
  • app/module/chat_history/mapper/chat_history.mapper.go - Entity to response mappers
  • app/module/chat_history/repository/chat_history.repository.go - Data access layer
  • app/module/chat_history/service/chat_history.service.go - Business logic layer
  • app/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 script
  • migrations/001_create_chat_history_tables.go - Go migration script
  • scripts/migrate.go - Migration runner script

API Endpoints

Chat History Endpoints

Sessions

  • GET /chat-history/sessions - Get user's chat sessions
  • GET /chat-history/sessions/{sessionId} - Get specific session with messages
  • POST /chat-history/sessions - Create new session
  • PUT /chat-history/sessions/{sessionId} - Update session
  • DELETE /chat-history/sessions/{sessionId} - Delete session

Messages

  • GET /chat-history/sessions/{sessionId}/messages - Get session messages
  • POST /chat-history/sessions/{sessionId}/messages - Create message
  • PUT /chat-history/messages/{messageId} - Update message
  • DELETE /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 sessions
  • GET /ai-chat/sessions/{id} - Get specific AI chat session
  • POST /ai-chat/sessions - Create AI chat session
  • PUT /ai-chat/sessions/{id} - Update AI chat session
  • DELETE /ai-chat/sessions/{id} - Delete AI chat session
  • GET /ai-chat/sessions/{sessionId}/messages - Get AI chat messages
  • POST /ai-chat/sessions/{sessionId}/messages - Send AI chat message
  • PUT /ai-chat/sessions/{sessionId}/messages/{messageId} - Update AI chat message
  • DELETE /ai-chat/sessions/{sessionId}/messages/{messageId} - Delete AI chat message
  • GET /ai-chat/logs - Get user's AI chat logs
  • GET /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

  1. Real-time Features: Add WebSocket support for real-time chat
  2. File Attachments: Support for file uploads in messages
  3. Message Search: Full-text search across messages
  4. Analytics: Chat analytics and reporting
  5. Export: Export chat history to various formats
  6. Archiving: Automatic archiving of old sessions

Troubleshooting

Common Issues

  1. Migration Errors: Ensure database connection is properly configured
  2. Authentication Errors: Verify Bearer token is valid and user exists
  3. Validation Errors: Check request payload matches expected schema
  4. 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.