Full-Stack Implementation of AI Conversation Assistant Based on Containerized Architecture

    This article outlines a containerized architecture solution for developing an AI conversation assistant, covering system design, core functionality implementation, engineering practices, and performance optimization strategies.

    System Architecture Design

    Containerization Advantages

    The solution implements frontend-backend separation through containerized deployment using Docker images to encapsulate complete runtime environments, ensuring consistency across development, testing, and production stages. Kubernetes-based dynamic resource scheduling enables elastic scaling to maintain service stability under high concurrency. Frontend containers contain only static assets and rendering logic, while backend containers integrate business services with middleware dependencies as independent service units.

    Technology Stack Selection

    The layered architecture follows these principles:

    • Frontend: Vue 3 composition API for code reusability, TypeScript for type safety, and Vite for rapid hot reloading
    • Service Layer: Express framework for lightweight HTTP services, SQLite as embedded database
    • Middleware: Redis for rate limiting, BullMQ for asynchronous task queues
    • Speech Processing: Browser MediaRecorder API for audio capture, whisper.cpp for local speech recognition

    Core Functionality Implementation

    Streaming Conversation Interface

    Server-Sent Events (SSE) enable real-time AI response streaming with chunked transfer encoding. The frontend establishes persistent connections via EventSource API to monitor three event types:

    1. // Frontend streaming implementation
    2. const eventSource = new EventSource(`/api/chat?stream=true`);
    3. eventSource.onmessage = (e) => {
    4. const data = JSON.parse(e.data);
    5. if (data.event === 'delta') updateChatContent(data.content);
    6. };

    Dual-Token Authentication

    The accessToken (15-minute validity) + refreshToken (7-day validity) system enables seamless token renewal:

    1. // Token refresh interceptor
    2. axios.interceptors.response.use(
    3. response => response,
    4. async (error) => {
    5. if (error.response.status === 401) {
    6. const { data } = await refreshToken();
    7. store.commit('updateTokens', data);
    8. return axios(error.config);
    9. }
    10. }
    11. );

    Voice Processing Pipeline

    1. Audio Capture: Web Audio API for standardized WAV output
    2. Asynchronous Transcription: BullMQ processes audio files through local whisper.cpp models
    3. Result Storage: Transcription text linked with original audio for message history
      ```javascript
      // Voice processing task definition
      const voiceQueue = new Bull(‘voice-processing’, {
      redis: process.env.REDIS_URL,
      defaultJobOptions: { attempts: 3, backoff: { type: ‘exponential’, delay: 1000 } }
      });

    voiceQueue.process(async (job) => {
    const { filePath } = job.data;
    const result = await whisper.transcribe(filePath);
    return await saveTranscription(result);
    });

    1. # Engineering Practices
    2. ## Monorepo Structure
    3. The project adopts a unified repository with clear module separation:

    .
    ├── ui/ # Frontend components
    │ ├── src/
    │ │ ├── api/ # API wrappers
    │ │ ├── hooks/ # Custom hooks
    │ │ └── utils/ # Utility functions
    ├── backend/ # Backend services
    │ ├── controllers/ # Route handlers
    │ ├── middleware/ # Middleware
    │ └── repositories/ # Data access
    └── docker-compose.yml # Container orchestration

    1. ## Container Build Optimization
    2. Multi-stage Docker builds minimize image sizes:
    3. ```dockerfile
    4. # Frontend build example
    5. FROM node:18-alpine as builder
    6. WORKDIR /app
    7. COPY ui/package*.json ./
    8. RUN npm install
    9. COPY ui/ .
    10. RUN npm run build
    11. FROM nginx:alpine
    12. COPY --from=builder /app/dist /usr/share/nginx/html
    13. COPY nginx.conf /etc/nginx/conf.d/default.conf

    Automated Observability

    Prometheus metrics integration with Grafana dashboards monitor:

    • API response time distribution
    • Voice processing queue backlog
    • Token refresh frequency
    • Database connection pool status

    Performance Optimization

    Rate Limiting Implementation

    Redis sliding window algorithm provides granular rate control:

    1. // Rate limiting middleware
    2. const rateLimiter = async (req, res, next) => {
    3. const key = `${req.ip}:${req.path}`;
    4. const now = Date.now();
    5. const windowSize = 60 * 1000; // 1-minute window
    6. let records = await redis.lrange(key, 0, -1);
    7. records = records.map(t => parseInt(t)).filter(t => now - t < windowSize);
    8. if (records.length >= 100) {
    9. return res.status(429).json({ error: 'Rate limit exceeded' });
    10. }
    11. records.push(now);
    12. await redis.rpush(key, ...records.slice(-99));
    13. await redis.expire(key, windowSize / 1000);
    14. next();
    15. };

    Database Optimization

    SQLite WAL mode improves concurrency with strategic indexing:

    1. -- Session table indexes
    2. CREATE INDEX idx_sessions_user ON sessions(user_id);
    3. CREATE INDEX idx_sessions_updated ON sessions(updated_at);
    4. -- Message table indexes
    5. CREATE INDEX idx_messages_session ON messages(session_id);
    6. CREATE INDEX idx_messages_timestamp ON messages(timestamp);

    Extensibility Design

    Model Plug-in Architecture

    Factory pattern enables dynamic AI model switching:

    1. interface IModelClient {
    2. generate(prompt: string): Promise<string>;
    3. }
    4. class ModelFactory {
    5. static create(type: 'openai' | 'deepseek'): IModelClient {
    6. switch(type) {
    7. case 'openai': return new OpenAIClient();
    8. case 'deepseek': return new DeepSeekClient();
    9. default: throw new Error('Unsupported model');
    10. }
    11. }
    12. }

    Multi-platform Adaptation

    Conditional compilation enables code reuse across H5 and mini-programs:

    1. // vite.config.js example
    2. export default defineConfig({
    3. plugins: [
    4. vue({
    5. template: {
    6. compilerOptions: {
    7. isCustomElement: (tag) => tag.startsWith('mp-') // Mini-program handling
    8. }
    9. }
    10. })
    11. ]
    12. });

    This containerized architecture provides a production-validated solution for rapid AI conversation system development. The approach enables seamless cloud migration and hybrid deployment while maintaining all core functionalities from streaming interaction to automated operations.