การเชื่อมต่อและใช้งาน DeepSeek API ใน PHP

DeepSeek เป็นโมเดลภาษาขนาดใหญ่ที่ทรงพลัง มีให้บริการผ่าน API ทำให้คุณสามารถนำความสามารถด้านการประมวลผลภาษาธรรมชาติไปใช้ในแอปพลิเคชัน PHP ของคุณได้อย่างง่ายดาย บทความนี้จะแนะนำขั้นตอนการเชื่อมต่อและใช้งาน DeepSeek API อย่างละเอียด พร้อมตัวอย่างโค้ดที่นำไปปรับใช้ได้จริง

เตรียม API Key

ก่อนอื่นคุณต้องสมัครใช้งานและรับ API Key จาก DeepSeek

  1. ไปที่ platform.deepseek.com
  2. ลงทะเบียนหรือเข้าสู่ระบบ
  3. ไปที่ส่วน API Keys แล้วคลิก Create new key
  4. คัดลอก API Key ที่ได้มาเก็บไว้อย่างปลอดภัย (จะเห็นแค่ครั้งเดียว)
⚠️ ข้อควรระวัง อย่าใส่ API Key ลงในโค้ดโดยตรงเมื่อขึ้น Production ควรใช้ตัวแปรสภาพแวดล้อมหรือไฟล์ config ที่ไม่ถูก commit ขึ้น Git

การเรียก DeepSeek API ด้วย cURL

DeepSeek ใช้ API endpoint เดียวกับ OpenAI (/v1/chat/completions) ดังนั้นโค้ดที่เขียนสำหรับ OpenAI ก็สามารถนำมาปรับใช้ได้ทันที

  • Endpoint https://api.deepseek.com/v1/chat/completions
  • Method POST
  • Headers
    • Authorization: Bearer YOUR_API_KEY
    • Content-Type: application/json

ตัวอย่างโครงสร้าง request body พื้นฐาน

{
    "model": "deepseek-chat",
    "messages": [
        {"role": "system", "content": "คุณคือผู้ช่วยที่เป็นประโยชน์"},
        {"role": "user", "content": "สวัสดี"}
    ]
}

สร้างฟังก์ชันสำหรับเรียก API

เราจะสร้างฟังก์ชัน PHP ที่รับข้อความจากผู้ใช้ ส่งไปยัง DeepSeek และคืนค่าคำตอบกลับมา

<?php
/**
 * ส่งข้อความไปยัง DeepSeek API และรับคำตอบกลับ
 *
 * @param string $userMessage ข้อความจากผู้ใช้
 * @param string $systemPrompt (optional) คำแนะนำระบบ
 * @param float $temperature (optional) ความสุ่มของคำตอบ (0-2)
 * @param int $maxTokens (optional) จำนวน token สูงสุด
 * @return string|false คำตอบจาก DeepSeek หรือ false หากเกิดข้อผิดพลาด
 */
function callDeepSeek($userMessage, $systemPrompt = "คุณคือผู้ช่วยที่มีประโยชน์และเป็นมิตร", $temperature = 0.7, $maxTokens = 1000)
{
    $apiKey = "YOUR_DEEPSEEK_API_KEY"; // แทนที่ด้วย API Key จริงของคุณ

    $url = "https://api.deepseek.com/v1/chat/completions";

    $data = [
        "model" => "deepseek-chat",
        "messages" => [
            ["role" => "system", "content" => $systemPrompt],
            ["role" => "user", "content" => $userMessage]
        ],
        "temperature" => $temperature,
        "max_tokens" => $maxTokens,
        "stream" => false
    ];

    $payload = json_encode($data);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Authorization: Bearer " . $apiKey
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60); // กำหนด timeout 60 วินาที

    $resp curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) {
        error_log("cURL Error: " . $curlError);
        return false;
    }

    if ($httpCode !== 200) {
        error_log("DeepSeek API Error (HTTP $httpCode): " . $response);
        return false;
    }

    $decoded = json_decode($response, true);
    if (isset($decoded['choices'][0]['message']['content'])) {
        return $decoded['choices'][0]['message']['content'];
    }

    error_log("Unexpected API response structure: " . print_r($decoded, true));
    return false;
}

ตัวอย่างการใช้งานจริง

ตัวอย่างที่ 1 การสนทนาพื้นฐาน

<?php
include 'deepseek_functions.php'; // สมมติว่าเก็บฟังก์ชันไว้ในไฟล์นี้

$question = "ขอโทษนะครับ ฉันช่วยอะไรคุณได้บ้าง?";
$answer = callDeepSeek($question);

if ($answer !== false) {
    echo "คำถาม: " . $question . "\n";
    echo "DeepSeek: " . $answer . "\n";
} else {
    echo "เกิดข้อผิดพลาดในการเชื่อมต่อกับ DeepSeek\n";
}

ตัวอย่างที่ 2 แชทบอทแบบโต้ตอบในหน้าเว็บ

[code]<!-- chat.php -->
<?php
session_start();
include 'deepseek_functions.php';

// กำหนด prompt ระบบสำหรับบอท
$systemPrompt = "คุณคือผู้ช่วยลูกค้าสัมพันธ์ของร้านขายหนังสือออนไลน์ " .
                "ตอบด้วยความสุภาพและให้ข้อมูลที่เป็นประโยชน์เกี่ยวกับหนังสือและการสั่งซื้อ";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    $userMessage = trim($_POST['message']);
    
    // เก็บประวัติการสนทนาใน session (แบบง่าย)
    if (!isset($_SESSION['chat_history'])) {
        $_SESSION['chat_history'] = [];
    }
    $_SESSION['chat_history'][] = ["role" => "user", "content" => $userMessage];
    
    // สร้างข้อความที่จะส่ง รวมประวัติล่าสุด 5 รายการ
    $messagesForAPI = [["role" => "system", "content" => $systemPrompt]];
    $recentHistory = array_slice($_SESSION['chat_history'], -5);
    foreach ($recentHistory as $msg) {
        $messagesForAPI[] = $msg;
    }
    
    // เรียก API (เราจะปรับฟังก์ชันเดิมให้รองรับ history แบบกำหนดเอง)
    $reply = callDeepSeekWithHistory($messagesForAPI);
    
    if ($reply !== false) {
        $_SESSION['chat_history'][] = ["role" => "assistant", "content" => $reply];
        echo json_encode(["success" => true, "reply" => $reply]);
    } else {
        echo json_encode(["success" => false, "error" => "ไม่สามารถติดต่อ DeepSeek ได้"]);
    }
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>แชทบอทด้วย DeepSeek</title>
    <style>
        #chatbox { border:1px solid #ccc; height:400px; overflow-y:scroll; padding:10px; margin-bottom:10px; }
        .user { text-align:right; color:blue; margin:5px; }
        .bot { text-align:left; color:green; margin:5px; }
    </style>
</head>
<body>
    <h1>DeepSeek แชทบอท</h1>
    <div id="chatbox"></div>
    <input type="text" id="messageInput" placeholder="พิมพ์ข้อความของคุณ..." style="width:80%">
    <button "sendMessage()">ส่ง</button>

    <script>
        function sendMessage() {
            let input = document.getElementById('messageInput');
            let msg = input.value.trim();
            if (!msg) return;
            
            // แสดงข้อความผู้ใช้
            let chatbox = document.getElementById('chatbox');
            let userDiv = document.createElement('div');
            userDiv.className = 'user';
            userDiv.textC 'คุณ: ' + msg;
            chatbox.appendChild(userDiv);
            chatbox.scrollTop = chatbox.scrollHeight;
            
            input.value = '';
            
            // ส่ง AJAX
            fetch('chat.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'message=' + encodeURIComponent(msg)
            })
            .then(res => res.json())
            .then(data => {
                let botDiv = document.createElement('div');
                botDiv.className = 'bot';