Tích hợp chatGPT(chat bot) vào dự án Laravel

Để tích hợp ChatGPT (OpenAI API) vào chatbot trong dự án Laravel của bạn, bạn sẽ cần thực hiện các bước sau, bao gồm cả backend và giao diện frontend (nếu có). Dưới đây là lộ trình đầy đủ theo từng bước: 

Laravel vs ChatGpt


✅ 1. Đăng ký OpenAI và lấy API key

  • Truy cập: https://platform.openai.com/
  • Tạo tài khoản (nếu chưa có).
  • Vào API Keys để tạo và lưu lại key (đừng để lộ public).


✅ 2. Cài gói Guzzle (nếu chưa có)

Laravel đã có sẵn Guzzle HTTP Client, nhưng nếu cần:

composer require guzzlehttp/guzzle

3. Tạo 1 service gọi đến OpenAI

Bạn có thể tạo 1 class service, ví dụ:

php artisan make:service ChatGPTService

Trong file app/Services/ChatGPTService.php:

php

namespace App\Services; use Illuminate\Support\Facades\Http; class ChatGPTService { protected string $endpoint = 'https://api.openai.com/v1/chat/completions'; public function ask(string $message, array $context = []): string { $response = Http::withToken(config('services.openai.key')) ->post($this->endpoint, [ 'model' => 'gpt-4', // hoặc 'gpt-3.5-turbo' 'messages' => array_merge($context, [ ['role' => 'user', 'content' => $message], ]), 'temperature' => 0.7, ]); return $response->json('choices.0.message.content') ?? 'No response'; } }

4. Thêm config key cho OpenAI

Trong .env:

env
OPENAI_API_KEY=your_openai_api_key_here

Trong config/services.php:

php
'openai' => [ 'key' => env('OPENAI_API_KEY'), ],

5. Tạo Controller để xử lý chatbot

bash
php artisan make:controller ChatbotController

Trong ChatbotController.php:

php
use App\Services\ChatGPTService; use Illuminate\Http\Request; public function ask(Request $request, ChatGPTService $chatGPT) { $validated = $request->validate([ 'message' => 'required|string', ]); $reply = $chatGPT->ask($validated['message']); return response()->json([ 'reply' => $reply, ]); }

6. Thêm route API

Trong routes/api.php:

php
Route::post('/chatbot/ask', [ChatbotController::class, 'ask']);

7. (Tuỳ chọn) Frontend hiển thị

Nếu bạn dùng Vue, React, hoặc Livewire:

  • Gửi AJAX request đến /api/chatbot/ask với message từ người dùng.
  • Hiển thị response trong phần chat.

Ví dụ đơn giản dùng fetch: 

javascript
const response = await fetch('/api/chatbot/ask', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({ message: 'Xin chào ChatGPT!' }) }); const data = await response.json(); console.log(data.reply);

8. (Tuỳ chọn nâng cao)

Bạn có thể: 

  • Ghi lại lịch sử hội thoại trong database.
  • Xây dựng conversation context (giữ nhiều message cũ trong messages).
  • Giao diện như real-time chat (xài Pusher hoặc Livewire).
  • Thêm role: “system” để định hướng hành vi của ChatGPT (ví dụ: đóng vai chuyên gia tư vấn luật).


Tổng kết

BướcMục tiêu
1Tạo OpenAI API Key
2Cài Guzzle
3Viết service gọi OpenAI
4Thêm cấu hình key
5Tạo controller xử lý
6Thêm route API
7(Tùy chọn) Hiển thị giao diện
8(Tùy chọn) Mở rộng logic Chat

Post a Comment

Previous Post Next Post