ภาพรวมระบบ
SmartPR Chatbot API เป็นระบบ AI Chatbot ที่ใช้เทคโนโลยี DeepSeek AI
และ RAG (Retrieval-Augmented Generation) เพื่อตอบคำถามจากฐานความรู้
💡 จุดเด่นของระบบ:
- ✅ ค้นหาข้อมูลจาก SQL Database อัตโนมัติ
- ✅ ใช้ AI ประมวลผลและตอบคำถาม
- ✅ รองรับการใช้งานผ่าน LINE Messaging API
- ✅ บันทึกประวัติการสนทนาทั้งหมด
🏗️ สถาปัตยกรรมระบบ
ผู้ใช้ส่งคำถาม
↓
LINE API ส่งไปที่ Webhook
↓
ระบบค้นหาความรู้จาก SQL (RAG)
↓
ส่งคำถาม + ความรู้ไปที่ DeepSeek AI
↓
AI ประมวลผลและตอบ
↓
ส่งคำตอบกลับผู้ใช้ผ่าน LINE
↓
บันทึกประวัติการสนทนา
LINE Webhook Endpoint
https://your-domain.com/pr_web/api/chatbot_webhook.php
Endpoint นี้รับ Webhook จาก LINE Messaging API และประมวลผลด้วย AI Chatbot
📥 Request Body (จาก LINE)
{
"events": [
{
"type": "message",
"replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
"source": {
"userId": "U4af4980629...",
"type": "user"
},
"message": {
"id": "325708",
"type": "text",
"text": "วิทยาลัยอยู่ที่ไหน?"
}
}
]
}
📤 Response (ส่งกลับไปที่ LINE)
{
"replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
"messages": [
{
"type": "text",
"text": "วิทยาลัยการอาชีพปราสาท ตั้งอยู่เลขที่ 191 หมู่ 15 ตำบลโคกยาง อำเภอปราสาท จังหวัดสุรินทร์ 32140\n\n📞 เบอร์โทรศัพท์: 044-545678\n🌐 เว็บไซต์: https://prasat.ac.th"
}
]
}
⚠️ หมายเหตุ: Endpoint นี้ใช้สำหรับ LINE Webhook เท่านั้น ต้องตั้งค่า Webhook URL ใน LINE Developers Console
⚙️ การตั้งค่า LINE Webhook
- ไปที่ LINE Developers Console
- เลือก Channel ของคุณ
- ไปที่ Messaging API tab
- ในส่วน Webhook settings:
- Webhook URL:
https://your-domain.com/pr_web/api/chatbot_webhook.php
- Use webhook: เปิด
- Auto-reply messages: ปิด
Knowledge Search API
https://your-domain.com/pr_web/api/knowledge_search.php
API สำหรับค้นหาความรู้จากฐานข้อมูล โดยใช้คีย์เวิร์ดและ FULLTEXT Search รองรับการใช้งานกับ n8n, Make, Zapier และระบบอัตโนมัติอื่นๆ
💡 คุณสมบัติ:
- ✅ ค้นหาอัตโนมัติด้วย Keyword Extraction
- ✅ รองรับภาษาไทยและภาษาอังกฤษ
- ✅ คำนวณความเกี่ยวข้อง (Relevance Score)
- ✅ รองรับทั้ง GET และ POST
- ✅ ระบบ Authentication ด้วย API Key
🔐 Authentication
ต้องใช้ API Key เดียวกับที่ตั้งค่าไว้ใน Chatbot Settings (DeepSeek API Key) สามารถส่งได้ 3 วิธี:
# วิธีที่ 1: Authorization Header (Bearer Token)
Authorization: Bearer sk-your-api-key-here
# วิธีที่ 2: X-API-Key Header
X-API-Key: sk-your-api-key-here
# วิธีที่ 3: Query Parameter
?api_key=sk-your-api-key-here
📋 Request Parameters
| Parameter |
Type |
Required |
Description |
query |
string |
Required |
คำถามหรือคีย์เวิร์ดที่ต้องการค้นหา |
limit |
integer |
Optional |
จำนวนผลลัพธ์สูงสุด (1-10, default: 3) |
api_key |
string |
Required |
API Key สำหรับยืนยันตัวตน (หรือใช้ Header แทน) |
📥 Request Examples
GET Request
curl -X GET "https://your-domain.com/pr_web/api/knowledge_search.php?query=วิทยาลัยอยู่ที่ไหน&limit=3" \
-H "Authorization: Bearer sk-your-api-key-here"
POST Request (JSON)
curl -X POST https://your-domain.com/pr_web/api/knowledge_search.php \
-H "Content-Type: application/json" \
-H "X-API-Key: sk-your-api-key-here" \
-d '{
"query": "วิทยาลัยมีสาขาอะไรบ้าง",
"limit": 5
}'
POST Request (Form Data)
curl -X POST https://your-domain.com/pr_web/api/knowledge_search.php \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "api_key=sk-your-api-key-here&query=วิทยาลัยเปิดรับสมัครเมื่อไหร่&limit=3"
📤 Response Format
Success Response (HTTP 200)
{
"success": true,
"query": "วิทยาลัยอยู่ที่ไหน",
"keywords": ["วิทยาลัย", "อยู่", "ที่ไหน"],
"total_results": 2,
"limit": 3,
"results": [
{
"id": 1,
"title": "ที่อยู่วิทยาลัย",
"content": "วิทยาลัยการอาชีพปราสาท ตั้งอยู่เลขที่ 191 หมู่ 15 ตำบลโคกยาง อำเภอปราสาท จังหวัดสุรินทร์ 32140",
"keywords": "ที่อยู่, วิทยาลัย, ปราสาท, สุรินทร์",
"category": "ข้อมูลทั่วไป",
"priority": 10,
"view_count": 156,
"relevance": 8.5,
"created_at": "2025-01-15 10:30:00",
"updated_at": "2025-01-15 10:30:00"
},
{
"id": 5,
"title": "ติดต่อวิทยาลัย",
"content": "เบอร์โทร: 044-545678, อีเมล: info@prasat.ac.th",
"keywords": "ติดต่อ, เบอร์โทร, อีเมล",
"category": "ข้อมูลการติดต่อ",
"priority": 5,
"view_count": 89,
"relevance": 3.2,
"created_at": "2025-01-15 11:00:00",
"updated_at": "2025-01-15 11:00:00"
}
]
}
Error Response Examples
// HTTP 401 - Missing API Key
{
"success": false,
"error": "API Key is required. Please provide via Authorization header or api_key parameter"
}
// HTTP 403 - Invalid API Key
{
"success": false,
"error": "Invalid API Key"
}
// HTTP 400 - Missing Query
{
"success": false,
"error": "Query parameter is required"
}
n8n Integration Guide
คู่มือการเชื่อมต่อ Knowledge Search API กับ n8n เพื่อสร้าง Workflow อัตโนมัติ
💡 Use Cases:
- 🔍 สร้างระบบค้นหาข้อมูลอัตโนมัติจากคำถามของผู้ใช้
- 🤖 เชื่อมต่อกับ Chatbot platforms อื่นๆ (Telegram, Facebook Messenger)
- 📊 สร้างระบบ FAQ อัตโนมัติ
- 📧 Auto-reply อีเมลด้วยข้อมูลจากฐานความรู้
🔧 การตั้งค่า n8n HTTP Request Node
Step 1: เพิ่ม HTTP Request Node
- เปิด n8n Workflow Editor
- เพิ่ม HTTP Request node
- ตั้งค่าดังนี้:
| Setting |
Value |
| Method |
POST |
| URL |
https://your-domain.com/pr_web/api/knowledge_search.php |
| Authentication |
Header Auth |
| Body Content Type |
JSON |
Step 2: ตั้งค่า Headers
เพิ่ม Header สำหรับ Authentication:
| Name |
Value |
X-API-Key |
sk-your-api-key-here |
Content-Type |
application/json |
Step 3: ตั้งค่า Request Body
{
"query": "{{ $json.message }}",
"limit": 3
}
หมายเหตุ: {{ $json.message }} จะดึงค่าจาก node ก่อนหน้า (เช่น Webhook, Trigger)
Step 4: ประมวลผล Response
เพิ่ม Code node หรือ Set node เพื่อประมวลผลข้อมูลที่ได้:
// ตัวอย่าง Code node สำหรับ format ข้อมูล
const results = $input.item.json.results;
if (results && results.length > 0) {
// สร้างข้อความจากผลลัพธ์
let response = "พบข้อมูลที่เกี่ยวข้อง:\\n\\n";
results.forEach((item, index) => {
response += `${index + 1}. ${item.title}\\n`;
response += `${item.content}\\n\\n`;
});
return {
json: {
found: true,
message: response,
total: results.length
}
};
} else {
return {
json: {
found: false,
message: "ไม่พบข้อมูลที่เกี่ยวข้อง"
}
};
}
📝 ตัวอย่าง n8n Workflow (JSON)
{
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "chatbot",
"responseMode": "responseNode",
"options": {}
},
"name": "Webhook",
"type": "n8n-nodes-base.webhook",
"position": [250, 300]
},
{
"parameters": {
"url": "https://your-domain.com/pr_web/api/knowledge_search.php",
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ { \"query\": $json.message, \"limit\": 3 } }}",
"options": {
"headers": {
"entries": [
{
"name": "X-API-Key",
"value": "sk-your-api-key-here"
}
]
}
}
},
"name": "Knowledge Search",
"type": "n8n-nodes-base.httpRequest",
"position": [450, 300]
},
{
"parameters": {
"respondWith": "json",
"responseBody": "={{ $json }}"
},
"name": "Respond to Webhook",
"type": "n8n-nodes-base.respondToWebhook",
"position": [650, 300]
}
],
"connections": {
"Webhook": {
"main": [[{"node": "Knowledge Search", "type": "main", "index": 0}]]
},
"Knowledge Search": {
"main": [[{"node": "Respond to Webhook", "type": "main", "index": 0}]]
}
}
}
🧪 ทดสอบ Workflow
ใช้ cURL ทดสอบ n8n Webhook:
curl -X POST https://your-n8n-instance.com/webhook/chatbot \
-H "Content-Type: application/json" \
-d '{
"message": "วิทยาลัยมีสาขาอะไรบ้าง"
}'
ผลลัพธ์ที่ได้รับ
{
"success": true,
"query": "วิทยาลัยมีสาขาอะไรบ้าง",
"total_results": 3,
"results": [
{
"title": "สาขาวิชาที่เปิดสอน",
"content": "วิทยาลัยการอาชีพปราสาท เปิดสอน 5 สาขา..."
}
]
}
💡 Tips:
- ✅ ใช้ Error Trigger node เพื่อจัดการข้อผิดพลาด
- ✅ เก็บ API Key ใน n8n Credentials แทนการ hardcode
- ✅ ใช้ IF node เพื่อตรวจสอบว่ามีผลลัพธ์หรือไม่
- ✅ เพิ่ม Retry logic เมื่อ API ล้มเหลว
API ทดสอบการสนทนา
https://your-domain.com/pr_web/admin/chatbot_test.php
API นี้ใช้สำหรับทดสอบการสนทนากับ AI Chatbot โดยตรง (ไม่ผ่าน LINE)
📋 Request Parameters
| Parameter |
Type |
Required |
Description |
action |
string |
Required |
ต้องเป็น "send_message" |
message |
string |
Required |
ข้อความคำถามที่ต้องการถาม AI |
📥 Request Example
curl -X POST https://your-domain.com/pr_web/admin/chatbot_test.php \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "action=send_message&message=วิทยาลัยมีสาขาอะไรบ้าง"
fetch('https://your-domain.com/pr_web/admin/chatbot_test.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
'action': 'send_message',
'message': 'วิทยาลัยมีสาขาอะไรบ้าง?'
})
})
.then(response => response.json())
.then(data => console.log(data));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://your-domain.com/pr_web/admin/chatbot_test.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'action' => 'send_message',
'message' => 'วิทยาลัยมีสาขาอะไรบ้าง?'
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
echo $result['response'];
📤 Response Example
✅ Success Response
{
"success": true,
"response": "สาขาวิชาที่เปิดสอน:\n\nระดับ ปวช.:\n• ช่างยนต์\n• ช่างไฟฟ้า\n• ช่างอิเล็กทรอนิกส์\n• คอมพิวเตอร์ธุรกิจ\n• การบัญชี\n• การตลาด\n\nระดับ ปวส.:\n• เทคนิคยานยนต์\n• เทคนิคไฟฟ้า\n• เทคโนโลยีสารสนเทศ\n• การบัญชี\n• การตลาด"
}
❌ Error Response
{
"success": false,
"error": "กรุณากรอกข้อความ"
}
Authentication
การใช้งาน API บางส่วนต้องมีการ Authentication
🔓 Public Endpoints (ไม่ต้อง Auth)
- ✅
/api/chatbot_webhook.php - LINE Webhook (ตรวจสอบ signature จาก LINE)
🔐 Protected Endpoints (ต้อง Auth)
- 🔒
/admin/chatbot_test.php - ต้อง Login Admin
- 🔒
/admin/chatbot_settings.php - ต้อง Login Admin
- 🔒
/admin/chatbot_knowledge.php - ต้อง Login Admin
💡 การ Login Admin: ใช้ระบบ Session-based Authentication
// ตัวอย่างการ Login
session_start();
if (isset($_SESSION['user_id']) && isset($_SESSION['user_role'])) {
// User is authenticated
}
ตัวอย่างการใช้งาน
📱 ตัวอย่างที่ 1: เชื่อมต่อ LINE Bot
// api/chatbot_webhook.php
require_once '../includes/chatbot_functions.php';
$input = file_get_contents('php://input');
$events = json_decode($input, true);
foreach ($events['events'] as $event) {
if ($event['type'] === 'message' && $event['message']['type'] === 'text') {
$userId = $event['source']['userId'];
$message = $event['message']['text'];
// ประมวลผลด้วย AI
$response = processChatbotMessage($userId, $message);
// ส่งคำตอบกลับ
replyMessage($event['replyToken'], $response);
}
}
🌐 ตัวอย่างที่ 2: เรียกใช้ผ่าน AJAX
// Frontend JavaScript
async function askChatbot(question) {
const formData = new FormData();
formData.append('action', 'send_message');
formData.append('message', question);
const response = await fetch('/pr_web/admin/chatbot_test.php', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.success) {
console.log('AI ตอบ:', result.response);
return result.response;
} else {
console.error('Error:', result.error);
return null;
}
}
// ใช้งาน
askChatbot('สมัครเรียนอย่างไร?').then(answer => {
document.getElementById('answer').textContent = answer;
});
🔌 ตัวอย่างที่ 3: Integration กับ Website
Error Codes
| HTTP Code |
Error Message |
Description |
Solution |
200 |
Success |
การประมวลผลสำเร็จ |
- |
400 |
กรุณากรอกข้อความ |
ไม่มีพารามิเตอร์ message |
ตรวจสอบว่าส่ง message มาด้วย |
401 |
Unauthorized |
ไม่มีสิทธิ์เข้าถึง |
Login ก่อนใช้งาน |
500 |
API Key not configured |
ยังไม่ได้ตั้งค่า API Key |
ไปที่ chatbot_settings.php เพื่อตั้งค่า |
500 |
Chatbot is disabled |
Chatbot ถูกปิดการใช้งาน |
เปิดใช้งานใน chatbot_settings.php |
🔍 Troubleshooting
วิธีตรวจสอบ Error:
- ตรวจสอบ Error Log:
/Applications/XAMPP/xamppfiles/logs/error_log
- ตรวจสอบว่า Chatbot เปิดใช้งานหรือไม่
- ตรวจสอบว่ามี API Key หรือไม่
- ทดสอบด้วย
/admin/chatbot_test.php ก่อน
ต้องการความช่วยเหลือ?
หากมีคำถามหรือพบปัญหา:
Made with ❤️ for วิทยาลัยการอาชีพปราสาท