Trong bài viết này, tôi sẽ chia sẻ cách áp dụng Domain-Driven Design (DDD) để xây dựng kiến trúc AI API có thể mở rộng, dựa trên kinh nghiệm thực chiến khi triển khai hệ thống chatbot chăm sóc khách hàng cho một sàn thương mại điện tử với 2 triệu người dùng hàng tháng. Trước đây, kiến trúc monolithic khiến team của tôi mất 3 ngày để deploy một tính năng nhỏ. Sau khi áp dụng DDD分层, thời gian giảm xuống còn 4 giờ, và quan trọng hơn, việc tích hợp model AI trở nên linh hoạt hơn bao giờ hết.
Tại Sao Cần DDD Cho AI API?
Khi làm việc với các AI API như GPT-4.1, Claude Sonnet 4.5, hay Gemini 2.5 Flash, việc gọi trực tiếp trong business logic dẫn đến code耦合 cao, khó test, và quan trọng nhất là không thể swap model khi giá thay đổi. Với mức giá chênh lệch lớn — từ $0.42/MTok (DeepSeek V3.2) đến $15/MTok (Claude Sonnet 4.5) — bạn cần một lớp trừu tượng để tối ưu chi phí theo từng use case.
Kiến Trúc DDD分层 Bốn Lớp
1. Domain Layer — Trái Tim Của Hệ Thống
Đây là lớp chứa business logic thuần túy, không phụ thuộc vào bất kỳ AI provider nào. Trong dự án thực tế, tôi định nghĩa các entity như Customer, Product, Intent để hệ thống hiểu nghiệp vụ mà không cần biết bên dưới dùng model gì.
// domain/entities/Customer.ts
export interface Customer {
id: string;
email: string;
tier: 'basic' | 'premium' | 'vip';
conversationHistory: Conversation[];
preferences: CustomerPreferences;
}
export interface Conversation {
id: string;
messages: Message[];
context: ConversationContext;
createdAt: Date;
resolvedAt?: Date;
}
export interface Message {
role: 'user' | 'assistant' | 'system';
content: string;
timestamp: Date;
metadata?: {
intent?: string;
confidence?: number;
modelUsed?: string;
};
}
export interface CustomerPreferences {
language: string;
communicationStyle: 'formal' | 'casual' | 'friendly';
allowedProductCategories: string[];
}
export type Intent =
| 'product_inquiry'
| 'order_status'
| 'refund_request'
| 'complaint'
| 'general_support';
export interface IntentClassification {
intent: Intent;
confidence: number;
entities: ExtractedEntity[];
}
export interface ExtractedEntity {
type: 'product_id' | 'order_id' | 'date' | 'amount';
value: string;
confidence: number;
}
2. Application Layer — Điều Phối Use Case
Lớp này chứa các service orchestration, xử lý business flow mà không quan tâm implementation chi tiết. Đây là nơi tôi implement các prompt template và response processing.
// application/services/CustomerSupportService.ts
import { Customer, IntentClassification } from '../../domain/entities/Customer';
import { AIProvider } from '../ports/AIProvider';
import { CustomerRepository } from '../ports/CustomerRepository';
export class CustomerSupportService {
constructor(
private aiProvider: AIProvider,
private customerRepo: CustomerRepository,
private responseCache: CacheService
) {}
async handleCustomerMessage(
customerId: string,
message: string
): Promise {
// Bước 1: Classify intent
const intent = await this.classifyIntent(message);
// Bước 2: Load customer context
const customer = await this.customerRepo.findById(customerId);
const context = this.buildContext(customer);
// Bước 3: Generate response với strategy phù hợp
const response = await this.generateResponse(
message,
intent,
context,
this.getStrategyForIntent(intent)
);
// Bước 4: Update conversation history
await this.updateConversation(customerId, message, response);
return response;
}
private async classifyIntent(message: string): Promise {
const systemPrompt = `Bạn là agent phân loại intent cho hệ thống chăm sóc khách hàng.
Phân loại tin nhắn vào một trong các intent: product_inquiry, order_status, refund_request, complaint, general_support.
Trả về JSON với fields: intent, confidence (0-1), entities (danh sách entities trích xuất được).`;
const response = await this.aiProvider.complete({
model: 'gpt-4.1',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: message }
],
temperature: 0.3,
maxTokens: 200
});
return JSON.parse(response.content);
}
private getStrategyForIntent(intent: Intent): ResponseStrategy {
const strategies: Record = {
product_inquiry: { model: 'gpt-4.1', temperature: 0.7, priority: 'high' },
order_status: { model: 'gpt-4.1', temperature: 0.2, priority: 'critical' },
refund_request: { model: 'claude-sonnet-4.5', temperature: 0.5, priority: 'high' },
complaint: { model: 'claude-sonnet-4.5', temperature: 0.6, priority: 'critical' },
general_support: { model: 'gemini-2.5-flash', temperature: 0.8, priority: 'low' }
};
return strategies[intent];
}
private async generateResponse(
message: string,
intent: IntentClassification,
context: ConversationContext,
strategy: ResponseStrategy
): Promise {
// Cache check cho các query thường gặp
const cacheKey = response:${hash(message)}:${intent.intent};
const cached = await this.responseCache.get(cacheKey);
if (cached && strategy.priority !== 'critical') return cached;
const startTime = Date.now();
const response = await this.aiProvider.complete({
model: strategy.model,
messages: [
{ role: 'system', content: this.buildSystemPrompt(context) },
...context.recentMessages,
{