AI System Architecture

CSKH AI trang web: Ranh giới năng lực và phương án kỹ thuật

CSKH AI của trang hiện là tanya-jawab tự động theo quy tắc (cơ sở kiến thức preset, không kết nối hồ sơ bệnh án, không gọi mô hình lớn bên ngoài); nội dung dưới đây là phương án kỹ thuật đang kế hoạch, dùng để giải thích tư tưởng thiết kế và triển khai tham khảo.

Giải thích trạng thái hiện tại:"CSKH AI" ở góc dưới bên phải trang làHỏi đáp tự động theo quy tắc, câu trả lời đến từ các mục kiến thức preset của trang này, không kết nối hồ sơ bệnh án cá nhân và không cấu thành lời khuyên y tế; cần hỗ trợ của con người hãy dùng "Tư vấn Miễn phí" hoặc WhatsApp, điều phối viên y tế sẽ liên hệ với bạn trong 24 giờ. Nội dung dưới đây làPhương án kỹ thuật đang kế hoạch, chưa ra mắt hết, chỉ để minh họa tư tưởng thiết kế và triển khai kỹ thuật.
Tổng quan kiến trúc

Kiến trúc tổng thể hệ thống

Đầu cuối
Giao diện hội thoại frontend · Web component / di động · đa ngôn ngữ · trợ năng
▼
Tích hợp
Cổng API · HTTPS/WSS · xác thực · giới hạn tốc độ
▼
Dịch vụ
Dịch vụ xử lý tin nhắn backend · quản lý phiên · định tuyến intent · rào chắn tuân thủ · lắp ráp ngữ cảnh
▼
Thông minh
Tích hợp API hội thoại mô hình lớn (kế hoạch) · tăng cường truy xuất RAG · Function Calling · đầu ra stream
Module sinh / sửa mã (hỗ trợ R&D, kế hoạch) · sinh mã intent và FAQ · PR tự sửa
▼
Dữ liệu
Cơ sở kiến thức KB / tìm kiếm vector
CRM / hệ thống ticket
Escalation tổng đài viên
Phân chia module

Trách nhiệm của bốn module cốt lõi

M1

Giao diện hội thoại frontend

Component React/Vue: danh sách tin nhắn, input, trạng thái đang gõ, chip nhanh, render stream, chuyển ngôn ngữ và trợ năng (aria / thao tác bàn phím).

M2

Dịch vụ xử lý tin nhắn backend

Trạng thái phiên, định tuyến intent, rào chắn tuân thủ, lắp ráp ngữ cảnh, gọi API mô hình lớn, kích hoạt chuyển cấp và kiểm toán nhật ký.

M3

Tích hợp API hội thoại mô hình lớn (kế hoạch)

API dịch vụ mô hình lớn: System Prompt tuân thủ y tế, tăng cường truy xuất RAG, Function Calling tra KB/CRM, trả lời stream SSE.

M4

Agent hỗ trợ R&D · sinh / sửa mã

Agent hỗ trợ R&D đang kế hoạch: sinh mã intent và FAQ mới, sửa lỗi, tạo PR, hợp vào sau khi review thủ công.

Luân chuyển dữ liệu

Chuỗi yêu cầu của một lượt hội thoại

  1. 1
    Người dùng gửi

    Frontend thu thập tin nhắn và sessionId, mã hóa qua WSS/HTTPS gửi lên /api/chat.

  2. 2
    Định tuyến intent

    Backend nhận diện intent theo từ khóa và mô hình phân loại (giá / mắt / du lịch / thành viên / khẩn cấp), và lắp ráp ngữ cảnh cùng đoạn cơ sở kiến thức.

  3. 3
    API hội thoại mô hình lớn generate

    Backend gọi API mô hình lớn (gồm rào chắn tuân thủ và RAG), trả về dạng stream SSE; nếu trúng điều kiện chuyển người thì định tuyến đến tổng đài viên.

  4. 4
    Render frontend

    Frontend render tăng dần phần trả lời, ghi nhật ký phiên và mức độ hài lòng, phục vụ lặp sau và tự sửa.

Chuỗi hỗ trợ R&D chạy độc lập: nhà phát triển nộp ticket (intent mới / Bug) → Agent sinh hoặc sửa mã → tạo Pull Request → review rồi hợp vào production.

Định nghĩa API

API then chốt / hợp đồng dữ liệu

POST /api/chat (SSE) request/response contract:

// Request
{
  "sessionId": "sess_8f3a",     // session id
  "message": "How much is a dental implant?",   // user text
  "lang": "en"                  // language
}
// Response (text/event-stream, chunked)
data: {"delta": "The indicative USD range for a single implant is ..."}
data: {"delta": "Final pricing follows the hospital."}
data: [DONE]

Hợp đồng gọi mô hình lớn (backend → dịch vụ mô hình):

POST https://api.openai.com/v1/chat/completions
{
  "model": "gpt-4o-mini",
  "stream": true,
  "messages": [
    {"role":"system","content":"compliance guardrails + KB snippets"},
    {"role":"user","content":"[en] How much is a dental implant?"}
  ]
}

Hợp đồng nhiệm vụ Agent hỗ trợ R&D (backend → Agent):

{
  "task": "Thêm câu hỏi FAQ cho intent giá: có bao gồm chi phí ghép xương không",
  "file": "src/intents/price.js",
  "failing_test": null,
  "review": "required"            // phải được review thủ công trước khi merge
}
Mã chạy được

Triển khai chức năng then chốt (chạy được ngay)

Dưới đây là cách viết ví dụ chung, chỉ để minh họa tư tưởng tích hợp,Không phải mã môi trường sản xuất của trang này, và chưa triển khai.

Dịch vụ xử lý tin nhắn backend + tích hợp mô hình lớn (Node 18+, cần express và openai):

// server.js
import express from 'express';
import OpenAI from 'openai';
const app = express();
app.use(express.json());
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

// Medical compliance guardrails: no diagnosis / prescriptions / efficacy promises
const GUARDRAILS = [
  'You are the AI assistant of a medical travel concierge site; provide objective process and credential information only.',
  'Never diagnose, prescribe, promise outcomes, or rank doctors.',
  'Actual treatment requires an in-person visit with a licensed physician; costs follow hospital pricing.',
  'For emergencies, guide users to local emergency numbers (120 in China / 911 in the US).',
  'When unsure, escalate to a human agent.'
].join(String.fromCharCode(10));

// Intent routing: keyword hit decides the class, otherwise general
const INTENTS = {
  price: /价格|比价|费用|报价|usd|\$/i,
  eye: /眼科|近视|激光|smile|lasik|icl|白内障/i,
  travel: /行程|签证|机票|酒店|陪护/i,
  member: /会员|登录|账号|保险/i,
  emergency: /紧急|急救|意外|危险/i
};
function route(text){ for(const k in INTENTS) if(INTENTS[k].test(text)) return k; return 'general'; }

app.post('/api/chat', async (req, res) => {
  const { sessionId, message, lang = 'zh-CN' } = req.body;
  const intent = route(message);
  const kb = await retrieveKB(intent, message); // vector retrieval placeholder
  const stream = await openai.chat.completions.create({
    model: 'gpt-4o-mini', stream: true,
    messages: [
      { role:'system', content: GUARDRAILS + '\nKB snippets:\n' + kb },
      { role:'user', content: '[' + lang + '] ' + message }
    ]
  });
  res.setHeader('Content-Type','text/event-stream');
  for await (const chunk of stream) {
    const t = (chunk.choices[0] && chunk.choices[0].delta && chunk.choices[0].delta.content) || '';
    if (t) res.write('data: ' + JSON.stringify({ delta: t }) + String.fromCharCode(10) + String.fromCharCode(10));
  }
  res.write('data: [DONE]' + String.fromCharCode(10) + String.fromCharCode(10));
  res.end();
});

async function retrieveKB(intent, q){ return '(Example) public credential and price-range notes for this intent.'; }
app.listen(3000, () => console.log('AI chat service on :3000'));

Gọi stream frontend (trình duyệt):

// chat-client.js
export async function sendChat(sessionId, message, lang, onDelta) {
  const res = await fetch('/api/chat', {
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({ sessionId, message, lang })
  });
  const reader = res.body.getReader();
  const dec = new TextDecoder();
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    for (const line of dec.decode(value).split(String.fromCharCode(10))) {
      if (line.startsWith('data: ')) {
        const payload = line.slice(6);
        if (payload === '[DONE]') return;
        onDelta(JSON.parse(payload).delta);
      }
    }
  }
}

Module sinh / sửa mã (hỗ trợ R&D, kế hoạch) (Python, cần openai, thay model khi tích hợp Agent hỗ trợ R&D):

# codex_agent.py
import os, openai, sys
client = openai.OpenAI(api_key=os.environ['OPENAI_API_KEY'])

def generate_or_fix(task, file_path=None, failing_test=None):
    ctx = ''
    if file_path and os.path.exists(file_path):
        ctx += '\n# Existing file ' + file_path + '\n' + open(file_path, encoding='utf-8').read()
    if failing_test:
        ctx += '\n# Failing test output\n' + failing_test
    prompt = ('You are the code engineer for the customer-service system. Task: ' + task +
              '\nOutput only a mergeable code diff or the complete file, with a brief explanation.\n' + ctx)
    r = client.chat.completions.create(
        model='gpt-4o',  # replace model when wiring in the actual code model
        messages=[{'role':'system','content':'You are a senior frontend / Node engineer familiar with this customer-service system.'},
                  {'role':'user','content':prompt}])
    return r.choices[0].message.content

if __name__ == '__main__':
    print(generate_or_fix(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None))
Lưu ý tuân thủ: mã ví dụ là minh họa kiến trúc, câu trả lời y tế phải chồng thêm rào chắn tuân thủ nghiêm ngặt và rà soát thủ công; API Key được tiêm qua biến môi trường, tuyệt đối không hardcode hay lộ ra frontend.