Production · chatbot.lks.ac.th

TCAS ChatBot

AI-Powered Chatbot for Thai University Admission (TCAS) Queries

Next.js Google Gemini AI RAG TypeScript Semantic Search Production

Overview

TCAS ChatBot is a Web Application powered by AI to answer questions about the Thai University Central Admission System (TCAS), referencing official data from the TCAS69 handbook published by CUPT. It features a Semantic Search for similar faculties, educational statistics, and Token-based Rate Limiting. Built with Next.js and Google Gemini AI, and currently live in production.

💡 Background & Importance

The TCAS admission system is complex and changes every year, leaving many students confused about application rounds, score requirements, and procedures. This project was developed as an AI Assistant capable of answering questions from reliable, official reference data. It uses the RAG (Retrieval-Augmented Generation) technique to ensure answers are accurate and traceable.

TCAS ChatBot หน้าหลัก
Main Page — AI-powered TCAS Q&A Chat Interface
TCAS ChatBot คณะใกล้เคียง
Similar Faculty Finder (Semantic Search)

System Architecture & Logic

Built with Next.js 15 (App Router) and TypeScript, using Google Gemini AI as the primary LLM for response generation. TCAS69 data is embedded as vectors using Text Embedding and stored for Semantic Search. The system includes Token-based Rate Limiting to prevent abuse and is deployed on a production server at chatbot.lks.ac.th.

# RAG Pipeline (Retrieval-Augmented Generation)

lib/ai/rag.ts
// RAG Pipeline: ค้นหาข้อมูล TCAS ที่เกี่ยวข้องก่อน Generate คำตอบ
async function generateChatResponse(userMessage: string) {
  // 1. Embed คำถามของผู้ใช้เป็น Vector
  const queryEmbedding = await embedText(userMessage);
  
  // 2. Semantic Search หาข้อมูล TCAS ที่ใกล้เคียงที่สุด
  const relevantChunks = await searchSimilarChunks(queryEmbedding, {
    topK: 5,
    threshold: 0.7,
  });
  
  // 3. สร้าง Context จากข้อมูลที่ค้นพบ
  const context = relevantChunks
    .map((chunk) => chunk.content)
    .join("\n\n---\n\n");
  
  // 4. ส่งให้ Gemini AI สร้างคำตอบโดยใช้ Context
  const response = await gemini.generateContent({
    contents: [{
      role: "user",
      parts: [{ text: buildPrompt(context, userMessage) }],
    }],
  });
  
  return response.text();
}

# Token Rate Limiting

lib/rateLimit.ts
// Token Rate Limiting: จำกัด 20 tokens ต่อ session
export async function checkAndDeductToken(
  sessionId: string
): Promise<{ allowed: boolean; remaining: number }> {
  const key = `tokens:${sessionId}`;
  const MAX_TOKENS = 20;
  
  const current = await redis.get(key);
  const used = current ? parseInt(current) : 0;
  
  if (used >= MAX_TOKENS) {
    return { allowed: false, remaining: 0 };
  }
  
  await redis.incr(key);
  await redis.expire(key, 86400); // Reset ทุก 24 ชั่วโมง
  
  return {
    allowed: true,
    remaining: MAX_TOKENS - used - 1,
  };
}

# Semantic Search (Similar Faculty)

lib/search/semantic.ts
// Semantic Search: ค้นหาคณะใกล้เคียงด้วย Cosine Similarity
function cosineSimilarity(vecA: number[], vecB: number[]): number {
  const dotProduct = vecA.reduce((sum, a, i) => sum + a * vecB[i], 0);
  const magnitudeA = Math.sqrt(vecA.reduce((sum, a) => sum + a * a, 0));
  const magnitudeB = Math.sqrt(vecB.reduce((sum, b) => sum + b * b, 0));
  return dotProduct / (magnitudeA * magnitudeB);
}

export async function findSimilarFaculties(
  targetFaculty: Faculty
): Promise<SimilarFaculty[]> {
  // Embed ชื่อและรายละเอียดคณะเป้าหมาย
  const targetEmbedding = await embedText(
    `${targetFaculty.name} ${targetFaculty.description}`
  );
  
  // คำนวณ Similarity กับทุกคณะในฐานข้อมูล
  const similarities = allFaculties.map((faculty) => ({
    faculty,
    score: cosineSimilarity(targetEmbedding, faculty.embedding),
  }));
  
  // เรียงลำดับและส่งคืน Top 10
  return similarities
    .sort((a, b) => b.score - a.score)
    .slice(1, 11); // ข้ามตัวเอง
}

Key Features

🤖

AI Chat: Real-time TCAS Q&A powered by Google Gemini AI

📚

RAG System: Grounds answers in official TCAS69 data from CUPT for accuracy

🔍

Similar Faculties: Find related university programs using Semantic Search

📊

Education Statistics: Displays TCAS application data and trends

🔒

Token Rate Limiting: 20 Tokens/Session limit for sustainable service

📱

Responsive Design: Fully optimized for both Mobile and Desktop screens

← Back to Portfolio