/
home
/
efamember
/
domains
/
efa-member.com
/
public_html
/
chat
/
up file
home
<?php header("Content-Type: application/json"); // ตั้งค่าการเชื่อมต่อฐานข้อมูล $host = "localhost"; $username = "bigdemo_tao"; // เปลี่ยนตามของคุณ $password = "f7KAdfoJv"; // เปลี่ยนตามของคุณ $database = "bigdemo_bigsara"; // เปลี่ยนตามของคุณ $conn = new mysqli($host, $username, $password, $database); if ($conn->connect_error) { die(json_encode(["reply" => "ไม่สามารถเชื่อมต่อกับฐานข้อมูล"])); } function cacheSchema($conn) { $tables_query = $conn->query("SHOW TABLES"); while ($row = $tables_query->fetch_array()) { $table = $row[0]; $columns_query = $conn->query("SHOW COLUMNS FROM $table"); $columns = []; while ($col = $columns_query->fetch_assoc()) { $columns[] = $col['Field']; } $column_list = implode(", ", $columns); // อัปเดตหรือเพิ่มข้อมูล schema $stmt = $conn->prepare("REPLACE INTO schema_cache (table_name, column_list) VALUES (?, ?)"); $stmt->bind_param("ss", $table, $column_list); $stmt->execute(); } } function getSchemaContext($conn) { $context = ""; $result = $conn->query("SELECT table_name, column_list FROM schema_cache"); while ($row = $result->fetch_assoc()) { $context .= "ตาราง: " . $row['table_name'] . "\n"; $context .= "คอลัมน์: " . $row['column_list'] . "\n\n"; } return $context; } // ใส่ OpenAI API Key ของคุณ $api_key = "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"; // รับข้อความจาก JavaScript $data = json_decode(file_get_contents("php://input"), true); $user_message = $data["message"]; // สร้าง context $context = "ข้อมูลฐานข้อมูล:\n"; $context .= getSchemaContext($conn); $context .= "ผู้ใช้ถาม: " . $user_message . "\n"; // ตรวจสอบหรืออัปเดต schema ถ้าจำเป็น (ครั้งเดียว หรือด้วย cron job) // cacheSchema($conn); // สามารถคอมเมนต์ออกถ้าไม่อยากเรียกทุกครั้ง // ส่งข้อความไปที่ OpenAI API $ch = curl_init("https://api.openai.com/v1/chat/completions"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Authorization: Bearer $api_key", "Content-Type: application/json" ]); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ "model" => "gpt-4o-mini", "messages" => [ ["role" => "system", "content" => "You are a chatbot that can answer questions about the database structure and its data."], ["role" => "user", "content" => $context] ] ])); $response = curl_exec($ch); curl_close($ch); $conn->close(); echo "<pre>"; var_dump($response_data); echo "</pre>"; // แปลงผลลัพธ์และส่งกลับ $response_data = json_decode($response, true); $reply = $response_data["choices"][0]["message"]["content"] ?? "เกิดข้อผิดพลาด"; echo json_encode(["reply" => $reply]); ?>