Thời gian đọc: 12 phút | Độ khó: Trung bình-cao | Cập nhật: Tháng 6/2026

Mở đầu: Câu chuyện từ một đêm deadline

Tôi vẫn nhớ rõ cái đêm tháng 3 năm 2026 — ngày ra mắt hệ thống RAG cho một doanh nghiệp thương mại điện tử lớn tại Việt Nam. Khách hàng của tôi phục vụ 50,000 người dùng đồng thời, và họ cần một giải pháp AI proxy vừa bảo mật, vừa có thể kiểm soát chi phí theo từng team. Đêm hôm đó, ngay trước giờ G, tôi phát hiện API key gốc của họ bị lộ trên GitHub public repository. May mắn là hệ thống proxy đã được tôi cấu hình trước đó đã ngăn chặn được thiệt hại.

Bài học từ trải nghiệm thực chiến đó: Không bao giờ để API key gốc tiếp xúc trực tiếp với client. Một authentication middleware không chỉ là lớp bảo mật — đó còn là cơ chế kiểm soát chi phí, rate limiting, và monitoring tập trung. Trong bài viết này, tôi sẽ hướng dẫn bạn xây dựng một AI API Proxy hoàn chỉnh với HolySheheep AI, platform mà tôi đã tin dùng từ đầu năm với mức giá tiết kiệm tới 85% so với các provider lớn khác.

Nếu bạn chưa có tài khoản, hãy đăng ký tại đây để nhận tín dụng miễn phí khi bắt đầu.

Tại sao cần AI API Proxy?

Trước khi đi vào code, hãy hiểu rõ vì sao authentication middleware lại quan trọng đến vậy:

Kiến trúc hệ thống

Hệ thống proxy của chúng ta sẽ có kiến trúc như sau:


┌─────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Client    │───▶│  Auth Middleware │───▶│  HolySheheep AI │
│  (Frontend) │    │  (Node.js/Go)    │    │  Proxy Server   │
└─────────────┘    └──────────────────┘    └─────────────────┘
                          │
                          ▼
                   ┌─────────────────┐
                   │   Redis Store   │
                   │ (Rate Limit DB) │
                   └─────────────────┘

Client gửi request kèm API key của proxy. Middleware xác thực key, kiểm tra rate limit, ghi log, sau đó chuyển tiếp request tới HolySheheep AI với base_url là https://api.holysheep.ai/v1.

Cài đặt môi trường

Tôi sẽ sử dụng Node.js với Express cho demonstration vì đây là stack phổ biến nhất trong các dự án AI tôi đã làm. Các dependency cần thiết:

# Khởi tạo project
mkdir ai-proxy-server
cd ai-proxy-server
npm init -y

Cài đặt dependencies

npm install express axios dotenv cors helmet express-rate-limit npm install --save-dev nodemon

Cài đặt Redis cho rate limiting (optional nhưng khuyến nghị)

Nếu không dùng Redis, hệ thống sẽ dùng in-memory store

Cấu trúc thư mục

ai-proxy-server/

├── src/

│ ├── index.js

│ ├── middleware/

│ │ ├── auth.js

│ │ ├── rateLimiter.js

│ │ └── logger.js

│ ├── routes/

│ │ └── proxy.js

│ └── utils/

│ └── holySheepClient.js

├── .env

└── package.json

Tạo Authentication Middleware

Authentication middleware là trái tim của hệ thống proxy. Nó sẽ xác thực API key từ client và gắn thông tin user vào request.

// src/middleware/auth.js
const API_KEYS = new Map();

// Khởi tạo API keys từ database hoặc file config
// Trong thực tế, nên lưu trong database với encrypted storage
const initializeAPIKeys = () => {
  // Format: API_KEY -> { userId, team, rateLimit, budget, expiresAt }
  API_KEYS.set('sk-proxy-client-001-prod', {
    userId: 'user_001',
    team: 'product_team',
    rateLimit: 100,        // 100 requests/phút
    monthlyBudget: 100,    // $100/tháng
    currentSpend: 0,
    expiresAt: new Date('2026-12-31'),
    permissions: ['chat', 'embeddings']
  });

  API_KEYS.set('sk-proxy-client-002-analytics', {
    userId: 'user_002',
    team: 'analytics_team',
    rateLimit: 200,        // 200 requests/phút
    monthlyBudget: 200,
    currentSpend: 0,
    expiresAt: new Date('2026-12-31'),
    permissions: ['chat', 'embeddings', 'completion']
  });
};

initializeAPIKeys();

const authMiddleware = async (req, res, next) => {
  try {
    // Lấy API key từ header
    const apiKey = req.headers['x-api-key'] || req.headers['authorization']?.replace('Bearer ', '');

    if (!apiKey) {
      return res.status(401).json({
        error: {
          code: 'MISSING_API_KEY',
          message: 'API key is required. Please provide x-api-key header.'
        }
      });
    }

    // Xác thực API key
    const keyData = API_KEYS.get(apiKey);

    if (!keyData) {
      // Ghi log request thất bại
      console.log([AUTH FAILED] Invalid API key attempt from IP: ${req.ip});
      return res.status(401).json({
        error: {
          code: 'INVALID_API_KEY',
          message: 'Invalid API key provided.'
        }
      });
    }

    // Kiểm tra expiration
    if (new Date() > keyData.expiresAt) {
      return res.status(401).json({
        error: {
          code: 'EXPIRED_API_KEY',
          message: 'API key has expired. Please renew your subscription.'
        }
      });
    }

    // Gắn thông tin user vào request
    req.apiKeyData = keyData;
    req.apiKey = apiKey;

    next();
  } catch (error) {
    console.error('[AUTH ERROR]', error);
    return res.status(500).json({
      error: {
        code: 'AUTH_SERVER_ERROR',
        message: 'Authentication service temporarily unavailable.'
      }
    });
  }
};

// Middleware kiểm tra quyền endpoint
const requirePermission = (...requiredPermissions) => {
  return (req, res, next) => {
    const userPermissions = req.apiKeyData.permissions;
    const hasPermission = requiredPermissions.every(perm => userPermissions.includes(perm));

    if (!hasPermission) {
      return res.status(403).json({
        error: {
          code: 'INSUFFICIENT_PERMISSION',
          message: This endpoint requires: ${requiredPermissions.join(', ')}
        }
      });
    }
    next();
  };
};

module.exports = { authMiddleware, requirePermission, API_KEYS };

Rate Limiter với Budget Control

Rate limiting không chỉ ngăn spam mà còn bảo vệ ngân sách của bạn. Với HolySheheep AI, việc theo dõi chi phí thật sự quan trọng vì:

// src/middleware/rateLimiter.js
const rateLimit = require('express-rate-limit');

// In-memory store cho rate limiting đơn giản
// Production nên dùng Redis
const requestCounts = new Map();

const rateLimiterMiddleware = (req, res, next) => {
  const keyData = req.apiKeyData;
  const windowMs = 60 * 1000; // 1 phút
  const now = Date.now();
  const windowStart = now - windowMs;

  // Lấy hoặc khởi tạo counter cho API key
  if (!requestCounts.has(req.apiKey)) {
    requestCounts.set(req.apiKey, {
      count: 0,
      resetTime: now + windowMs,
      requestHistory: []
    });
  }

  const keyCounter = requestCounts.get(req.apiKey);

  // Reset counter nếu hết window
  if (now > keyCounter.resetTime) {
    keyCounter.count = 0;
    keyCounter.resetTime = now + windowMs;
    keyCounter.requestHistory = [];
  }

  // Kiểm tra rate limit
  if (keyCounter.count >= keyData.rateLimit) {
    const retryAfter = Math.ceil((keyCounter.resetTime - now) / 1000);
    res.setHeader('X-RateLimit-Limit', keyData.rateLimit);
    res.setHeader('X-RateLimit-Remaining', 0);
    res.setHeader('X-RateLimit-Reset', keyCounter.resetTime);
    res.setHeader('Retry-After', retryAfter);

    return res.status(429).json({
      error: {
        code: 'RATE_LIMIT_EXCEEDED',
        message: Rate limit exceeded. Limit: ${keyData.rateLimit} requests/minute. Retry after ${retryAfter}s.,
        retryAfter: retryAfter
      }
    });
  }

  // Tăng counter
  keyCounter.count++;
  keyCounter.requestHistory.push(now);

  // Set headers
  res.setHeader('X-RateLimit-Limit', keyData.rateLimit);
  res.setHeader('X-RateLimit-Remaining', keyData.rateLimit - keyCounter.count);
  res.setHeader('X-RateLimit-Reset', keyCounter.resetTime);

  next();
};

// Middleware kiểm tra budget
const budgetMiddleware = async (req, res, next) => {
  const keyData = req.apiKeyData;
  const estimatedCost = estimateRequestCost(req.body);

  // Lấy spending từ database thực tế
  const currentSpend = await getActualSpending(keyData.userId);

  if (currentSpend + estimatedCost > keyData.monthlyBudget) {
    return res.status(402).json({
      error: {
        code: 'BUDGET_EXCEEDED',
        message: Monthly budget exceeded. Current spend: $${currentSpend.toFixed(2)}, Budget: $${keyData.monthlyBudget},
        currentSpend: currentSpend,
        budget: keyData.monthlyBudget
      }
    });
  }

  // Gắn estimated cost để cập nhật sau khi request hoàn thành
  req.estimatedCost = estimatedCost;
  req.keyData = keyData;

  next();
};

// Ước tính chi phí dựa trên request (cần điều chỉnh theo model)
const estimateRequestCost = (body) => {
  const model = body.model || 'gpt-4.1';
  const promptTokens = body.messages?.reduce((sum, msg) => sum + (msg.content?.length || 0) / 4, 0) || 0;

  const costPerMTok = {
    'gpt-4.1': 8,
    'gpt-4o': 5,
    'claude-sonnet-4.5': 15,
    'gemini-2.5-flash': 2.5,
    'deepseek-v3.2': 0.42
  };

  const cost = (promptTokens / 1_000_000) * (costPerMTok[model] || 8);
  return Math.max(cost, 0.001); // Minimum $0.001
};

// Lấy chi tiêu thực tế từ database
const getActualSpending = async (userId) => {
  // Trong thực tế, query từ database
  // Ví dụ: SELECT SUM(cost) FROM usage_logs WHERE user_id = ? AND created_at >= DATE_TRUNC('month', NOW())
  return 0; // Placeholder
};

module.exports = { rateLimiterMiddleware, budgetMiddleware };

HolySheheep AI Proxy Client

Đây là phần core nhất — kết nối tới HolySheheep AI với base_url đúng. Lưu ý quan trọng: Luôn sử dụng base_url là https://api.holysheep.ai/v1.

// src/utils/holySheepClient.js
const axios = require('axios');

// HolySheheep AI Configuration
const HOLYSHEEP_CONFIG = {
  baseURL: 'https://api.holysheep.ai/v1',
  timeout: 120000, // 2 phút cho các model lớn
  maxRetries: 3
};

// Tạo axios instance cho HolySheheep
const holySheepClient = axios.create({
  baseURL: HOLYSHEEP_CONFIG.baseURL,
  timeout: HOLYSHEEP_CONFIG.timeout,
  headers: {
    'Content-Type': 'application/json'
  }
});

// Retry logic cho transient errors
holySheepClient.interceptors.response.use(
  response => response,
  async error => {
    const config = error.config;

    if (!config || !HOLYSHEEP_CONFIG.maxRetries) {
      return Promise.reject(error);
    }

    config.__retryCount = config.__retryCount || 0;

    // Retry cho các lỗi tạm thời
    const shouldRetry = error.code === 'ECONNRESET' ||
                        error.code === 'ETIMEDOUT' ||
                        error.response?.status === 429 ||
                        error.response?.status >= 500;

    if (shouldRetry && config.__retryCount < HOLYSHEEP_CONFIG.maxRetries) {
      config.__retryCount++;
      const delay = Math.pow(2, config.__retryCount) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
      return holySheepClient(config);
    }

    return Promise.reject(error);
  }
);

// Proxy endpoint cho Chat Completion
const proxyChatCompletion = async (req, res) => {
  try {
    const { messages, model, temperature, max_tokens, ...restParams } = req.body;
    const holysheepApiKey = process.env.HOLYSHEEP_API_KEY;

    // Validate model
    const allowedModels = [
      'gpt-4.1',
      'gpt-4o',
      'gpt-4o-mini',
      'claude-sonnet-4.5',
      'claude-opus-4',
      'gemini-2.5-flash',
      'deepseek-v3.2'
    ];

    if (!allowedModels.includes(model)) {
      return res.status(400).json({
        error: {
          code: 'INVALID_MODEL',
          message: Model '${model}' is not supported. Allowed: ${allowedModels.join(', ')}
        }
      });
    }

    const startTime = Date.now();

    // Gọi HolySheheep AI
    const response = await holySheepClient.post('/chat/completions', {
      model: model,
      messages: messages,
      temperature: temperature || 0.7,
      max_tokens: max_tokens || 4096,
      ...restParams
    }, {
      headers: {
        'Authorization': Bearer ${holysheepApiKey}
      }
    });

    const latency = Date.now() - startTime;

    // Ghi log usage
    await logUsage({
      userId: req.apiKeyData.userId,
      apiKey: req.apiKey,
      model: model,
      promptTokens: response.data.usage?.prompt_tokens || 0,
      completionTokens: response.data.usage?.completion_tokens || 0,
      totalTokens: response.data.usage?.total_tokens || 0,
      cost: calculateCost(model, response.data.usage),
      latency: latency,
      timestamp: new Date()
    });

    // Set proxy-specific headers
    res.setHeader('X-Proxy-Latency', latency);
    res.setHeader('X-Proxy-Provider', 'HolySheheep AI');

    return res.json(response.data);
  } catch (error) {
    console.error('[HOLYSHEEP ERROR]', error.response?.data || error.message);
    return handleProxyError(error, res);
  }
};

// Proxy endpoint cho Embeddings
const proxyEmbeddings = async (req, res) => {
  try {
    const { input, model } = req.body;
    const holysheepApiKey = process.env.HOLYSHEEP_API_KEY;

    const startTime = Date.now();
    const response = await holySheepClient.post('/embeddings', {
      input: input,
      model: model || 'text-embedding-3-small'
    }, {
      headers: {
        'Authorization': Bearer ${holysheepApiKey}
      }
    });

    const latency = Date.now() - startTime;

    await logUsage({
      userId: req.apiKeyData.userId,
      apiKey: req.apiKey,
      model: model || 'text-embedding-3-small',
      type: 'embeddings',
      tokens: response.data.usage?.total_tokens || 0,
      cost: (response.data.usage?.total_tokens || 0) / 1_000_000 * 0.02, // $0.02/MTok
      latency: latency
    });

    res.setHeader('X-Proxy-Latency', latency);
    res.setHeader('X-Proxy-Provider', 'HolySheheep AI');

    return res.json(response.data);
  } catch (error) {
    return handleProxyError(error, res);
  }
};

// Tính chi phí
const calculateCost = (model, usage) => {
  const pricing = {
    'gpt-4.1': { input: 8, output: 8 },
    'gpt-4o': { input: 5, output: 15 },
    'gpt-4o-mini': { input: 0.15, output: 0.6 },
    'claude-sonnet-4.5': { input: 15, output: 15 },
    'claude-opus-4': { input: 30, output: 90 },
    'gemini-2.5-flash': { input: 2.5, output: 2.5 },
    'deepseek-v3.2': { input: 0.42, output: 0.42 }
  };

  const modelPricing = pricing[model] || pricing['gpt-4.1'];
  const inputCost = (usage?.prompt_tokens || 0) / 1_000_000 * modelPricing.input;
  const outputCost = (usage?.completion_tokens || 0) / 1_000_000 * modelPricing.output;

  return inputCost + outputCost;
};

// Xử lý lỗi proxy
const handleProxyError = (error, res) => {
  if (error.response) {
    return res.status(error.response.status).json({
      error: {
        code: error.response.data?.error?.code || 'PROVIDER_ERROR',
        message: error.response.data?.error?.message || 'HolySheheep API error',
        details: error.response.data
      }
    });
  }

  if (error.code === 'ECONNABORTED') {
    return res.status(504).json({
      error: {
        code: 'TIMEOUT',
        message: 'Request to AI provider timed out. Please try again.'
      }
    });
  }

  return res.status(502).json({
    error: {
      code: 'PROXY_ERROR',
      message: 'Proxy server error. Please try again later.'
    }
  });
};

// Log usage (implement với database thực tế)
const logUsage = async (logData) => {
  // Trong thực tế, ghi vào PostgreSQL/MongoDB/Elasticsearch
  console.log('[USAGE LOG]', JSON.stringify(logData));
};

module.exports = {
  holySheepClient,
  proxyChatCompletion,
  proxyEmbeddings
};

Main Server Entry Point

// src/index.js
require('dotenv').config();
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const { authMiddleware, requirePermission } = require('./middleware/auth');
const { rateLimiterMiddleware, budgetMiddleware } = require('./middleware/rateLimiter');
const { proxyChatCompletion, proxyEmbeddings } = require('./utils/holySheepClient');

const app = express();
const PORT = process.env.PORT || 3000;

// Security middleware
app.use(helmet({
  contentSecurityPolicy: false // Disable CSP for API
}));
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(',') || '*',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type', 'Authorization', 'x-api-key']
}));

// Parse JSON bodies
app.use(express.json({ limit: '10mb' }));

// Request logging
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    const duration = Date.now() - start;
    console.log([${new Date().toISOString()}] ${req.method} ${req.path} - ${res.statusCode} (${duration}ms));
  });
  next();
});

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({
    status: 'healthy',
    provider: 'HolySheheep AI Proxy',
    timestamp: new Date().toISOString(),
    version: '1.0.0'
  });
});

// ============ AI PROXY ROUTES ============

// Chat Completion Proxy
// POST /api/v1/chat/completions
app.post(
  '/api/v1/chat/completions',
  authMiddleware,
  rateLimiterMiddleware,
  budgetMiddleware,
  requirePermission('chat'),
  proxyChatCompletion
);

// Embeddings Proxy
// POST /api/v1/embeddings
app.post(
  '/api/v1/embeddings',
  authMiddleware,
  rateLimiterMiddleware,
  budgetMiddleware,
  requirePermission('embeddings'),
  proxyEmbeddings
);

// List available models
app.get('/api/v1/models', authMiddleware, (req, res) => {
  res.json({
    object: 'list',
    data: [
      {
        id: 'gpt-4.1',
        object: 'model',
        created: 1704067200,
        owned_by: 'HolySheheep AI',
        input_cost_per_mtok: 8,
        output_cost_per_mtok: 8
      },
      {
        id: 'claude-sonnet-4.5',
        object: 'model',
        created: 1704067200,
        owned_by: 'HolySheheep AI',
        input_cost_per_mtok: 15,
        output_cost_per_mtok: 15
      },
      {
        id: 'gemini-2.5-flash',
        object: 'model',
        created: 1704067200,
        owned_by: 'HolySheheep AI',
        input_cost_per_mtok: 2.5,
        output_cost_per_mtok: 2.5
      },
      {
        id: 'deepseek-v3.2',
        object: 'model',
        created: 1704067200,
        owned_by: 'HolySheheep AI',
        input_cost_per_mtok: 0.42,
        output_cost_per_mtok: 0.42
      }
    ]
  });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error('[SERVER ERROR]', err);
  res.status(500).json({
    error: {
      code: 'INTERNAL_ERROR',
      message: 'Internal server error'
    }
  });
});

// 404 handler
app.use((req, res) => {
  res.status(404).json({
    error: {
      code: 'NOT_FOUND',
      message: Endpoint ${req.method} ${req.path} not found
    }
  });
});

// Start server
app.listen(PORT, () => {
  console.log(`
╔════════════════════════════════════════════════════════════╗
║          HolySheheep AI Proxy Server Started               ║
╠════════════════════════════════════════════════════════════╣
║  Port: ${PORT}                                               ║
║  Provider: https://api.holysheep.ai/v1                     ║
║  Environment: ${process.env.NODE_ENV || 'development'}                             ║
╚════════════════════════════════════════════════════════════╝
  `);
});

module.exports = app;

Tạo API Key cho Client

Để tạo và quản lý API keys cho clients, tôi khuyến nghị tạo một endpoint riêng:

// src/routes/admin.js (bổ sung vào index.js)
const crypto = require('crypto');

// Tạo API key mới
app.post('/admin/api-keys', async (req, res) => {
  const { userId, team, rateLimit, monthlyBudget, permissions } = req.body;

  // Validate admin access (thêm auth riêng cho admin)
  const adminKey = req.headers['x-admin-key'];
  if (adminKey !== process.env.ADMIN_SECRET) {
    return res.status(403).json({ error: 'Admin access required' });
  }

  // Generate API key
  const apiKey = sk-proxy-${crypto.randomBytes(16).toString('hex')};
  const expiresAt = new Date();
  expiresAt.setMonth(expiresAt.getMonth() + 1);

  // Lưu vào database
  const keyData = {
    userId,
    team,
    rateLimit: rateLimit || 60,
    monthlyBudget: monthlyBudget || 50,
    currentSpend: 0,
    expiresAt,
    permissions: permissions || ['chat', 'embeddings']
  };

  // Trong thực tế: INSERT INTO api_keys VALUES (...)
  API_KEYS.set(apiKey, keyData);

  res.json({
    success: true,
    apiKey: apiKey,
    expiresAt: expiresAt,
    message: 'API key created successfully. Store it securely - it will not be shown again.'
  });
});

// Revoke API key
app.delete('/admin/api-keys/:key', async (req, res) => {
  const adminKey = req.headers['x-admin-key'];
  if (adminKey !== process.env.ADMIN_SECRET) {
    return res.status(403).json({ error: 'Admin access required' });
  }

  if (!API_KEYS.has(req.params.key)) {
    return res.status(404).json({ error: 'API key not found' });
  }

  API_KEYS.delete(req.params.key);
  res.json({ success: true, message: 'API key revoked' });
});

// Get usage statistics
app.get('/admin/usage/:key', async (req, res) => {
  const adminKey = req.headers['x-admin-key'];
  if (adminKey !== process.env.ADMIN_SECRET) {
    return res.status(403).json({ error: 'Admin access required' });
  }

  const keyData = API_KEYS.get(req.params.key);
  if (!keyData) {
    return res.status(404).json({ error: 'API key not found' });
  }

  res.json({
    apiKey: req.params.key.slice(0, 10) + '...',
    userId: keyData.userId,
    team: keyData.team,
    monthlyBudget: keyData.monthlyBudget,
    currentSpend: keyData.currentSpend,
    rateLimit: keyData.rateLimit,
    expiresAt: keyData.expiresAt
  });
});

Client Usage Example

Dưới đây là ví dụ cách client sử dụng proxy:

// client-example.js
// Ví dụ sử dụng AI Proxy với frontend

const AI_PROXY_BASE_URL = 'https://your-proxy-domain.com';
const CLIENT_API_KEY = 'sk-proxy-client-001-prod'; // API key được cấp phát

async function chatCompletion(messages, model = 'deepseek-v3.2') {
  try {
    const response = await fetch(${AI_PROXY_BASE_URL}/api/v1/chat/completions, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': CLIENT_API_KEY
      },
      body: JSON.stringify({
        model: model,
        messages: messages,
        temperature: 0.7,
        max_tokens: 2000
      })
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error?.message || 'Request failed');
    }

    const data = await response.json();

    // Kiểm tra headers để biết thêm thông tin
    console.log('Rate Limit Remaining:', response.headers.get('X-RateLimit-Remaining'));
    console.log('Proxy Latency:', response.headers.get('X-Proxy-Latency'), 'ms');
    console.log('Provider:', response.headers.get('X-Proxy-Provider'));

    return data;
  } catch (error) {
    console.error('AI Proxy Error:', error.message);
    throw error;
  }
}

// Ví dụ gọi từ React/Vue/Angular
async function main() {
  const messages = [
    { role: 'system', content: 'Bạn là trợ lý AI tiếng Việt hữu ích.' },
    { role: 'user', content: 'Giải thích về RAG system trong 3 câu.' }
  ];

  try {
    const result = await chatCompletion(messages, 'deepseek-v3.2');
    console.log('Response:', result.choices[0].message.content);
    console.log('Total Tokens:', result.usage.total_tokens);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

main();

Tối ưu hóa hiệu suất

Qua nhiều dự án, tôi đã rút ra một số best practices để tối ưu proxy:

// Cấu hình tối ưu trong index.js
const http = require('http');
const https = require('https');

// Tăng connection limits
http.globalAgent.maxSockets = 100;
https.globalAgent.maxSockets = 100;

// Compress responses lớn
const compression = require('compression');
app.use(compression({
  threshold: 1024 // Compress responses > 1KB
}));

// Redis cache cho embeddings (nếu dùng)
const Redis = require('ioredis');
const redis = new Redis(process.env.REDIS_URL);

// Cache embeddings
const cacheEmbedding = async (text, embedding) => {
  const hash = require('crypto').createHash('sha256').update(text).digest('hex');
  await redis.setex(emb:${hash}, 86400, JSON.stringify(embedding)); // TTL 24h