Integrasi AI di Laravel: Membangun Fitur Cerdas untuk Aplikasi Web
Menggabungkan kekuatan Laravel dengan AI membuka banyak peluang untuk membangun fitur cerdas di aplikasi web Anda.
Persiapan Project
composer create-project laravel/laravel ai-laravel
cd ai-laravel
composer require openai-php/laravel
Tambahkan API key di .env:
OPENAI_API_KEY=sk-...
OPENAI_ORGANIZATION=org-...
GEMINI_API_KEY=AIzaSy...
Fitur 1: Auto-Generate Blog Content
// app/Services/AIContentService.php
namespace App\Services;
use OpenAI\Laravel\Facades\OpenAI;
use Illuminate\Support\Facades\Http;
class AIContentService
{
public function generateArticle(string $topic, string $style = 'informatif'): array
{
$response = OpenAI::chat()->create([
'model' => 'gpt-4o-mini',
'messages' => [
[
'role' => 'system',
'content' => "Kamu adalah content writer profesional Indonesia.
Tulis artikel {$style} dalam format Markdown."
],
[
'role' => 'user',
'content' => "Buatkan artikel lengkap tentang: {$topic}.
Sertakan heading, subheading, code examples jika relevan,
dan kesimpulan. Minimal 600 kata."
],
],
'max_tokens' => 2048,
'temperature' => 0.7,
]);
$content = $response->choices[0]->message->content;
// Extract title dari content
preg_match('/^#\s+(.+)$/m', $content, $matches);
$title = $matches[1] ?? $topic;
return [
'title' => $title,
'content' => $content,
'excerpt' => Str::limit(strip_tags($content), 200),
];
}
public function generateWithGemini(string $topic): string
{
$response = Http::withHeaders([
'Content-Type' => 'application/json',
])->post(
'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=' .
config('services.gemini.api_key'),
[
'contents' => [
[
'role' => 'user',
'parts' => [
['text' => "Buatkan artikel teknikal tentang: {$topic}. Format Markdown, bahasa Indonesia."]
]
]
],
'generationConfig' => [
'maxOutputTokens' => 2048,
'temperature' => 0.8,
],
]
);
return $response->json('candidates.0.content.parts.0.text', '');
}
}
Fitur 2: AI-Powered Search dan Rekomendasi
// app/Services/AISearchService.php
namespace App\Services;
use OpenAI\Laravel\Facades\OpenAI;
use App\Models\Article;
class AISearchService
{
public function smartSearch(string $query): array
{
// Ambil semua articles (untuk dataset kecil)
$articles = Article::select('id', 'title', 'excerpt')
->where('is_published', true)
->get();
$response = OpenAI::chat()->create([
'model' => 'gpt-4o-mini',
'messages' => [
[
'role' => 'system',
'content' => 'Kamu adalah search assistant. Berikan ID artikel
yang paling relevan dengan query user. Jawab dalam
format JSON: {"ids": [1, 2, 3], "reason": "..."}'
],
[
'role' => 'user',
'content' => "Query: {$query}\n\nArtikel:\n" .
$articles->map(fn($a) => "{$a->id}: {$a->title} - {$a->excerpt}")
->implode("\n")
],
],
]);
return json_decode($response->choices[0]->message->content, true);
}
}
Fitur 3: Auto-Reply Customer Support
// app/Services/AIReplyService.php
namespace App\Services;
use OpenAI\Laravel\Facades\OpenAI;
class AIReplyService
{
private string $systemPrompt;
public function __construct()
{
$this->systemPrompt = <<<PROMPT
Kamu adalah customer support AI untuk PT Digitcode Studio Teknologi.
Info perusahaan:
- Layanan: Web development, Mobile app, System integration
- Jam kerja: Senin-Jumat 09:00-17:00 WIB
- Email: digitcode.id@gmail.com
- Telepon: 0813-1360-0301
Aturan:
- Jawab dengan ramah dan profesional dalam Bahasa Indonesia
- Jika pertanyaan di luar scope, arahkan ke email atau telepon
- Jangan memberikan informasi harga pasti, arahkan ke konsultasi
PROMPT;
}
public function reply(string $message, array $context = []): string
{
$messages = [
['role' => 'system', 'content' => $this->systemPrompt],
];
// Tambahkan history jika ada
foreach ($context as $msg) {
$messages[] = $msg;
}
$messages[] = ['role' => 'user', 'content' => $message];
$response = OpenAI::chat()->create([
'model' => 'gpt-4o-mini',
'messages' => $messages,
'max_tokens' => 512,
'temperature' => 0.6,
]);
return $response->choices[0]->message->content;
}
}
Fitur 4: Artisan Command untuk Batch Processing
// app/Console/Commands/GenerateContent.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Services\AIContentService;
use App\Models\Article;
class GenerateContent extends Command
{
protected $signature = 'ai:generate {topic} {--publish}';
protected $description = 'Generate artikel menggunakan AI';
public function handle(AIContentService $ai): int
{
$topic = $this->argument('topic');
$this->info("Generating article about: {$topic}...");
$result = $ai->generateArticle($topic);
$article = Article::create([
'title' => $result['title'],
'slug' => Str::slug($result['title']),
'content' => $result['content'],
'excerpt' => $result['excerpt'],
'is_published' => $this->option('publish'),
]);
$this->info("Article created: {$article->title}");
return Command::SUCCESS;
}
}
Tips Keamanan untuk AI Integration
- Rate limiting — Batasi request AI per user
- Input sanitization — Bersihkan input sebelum kirim ke AI
- Output filtering — Filter response AI sebelum tampilkan ke user
- Cost monitoring — Monitor penggunaan API untuk kontrol biaya
- Fallback mechanism — Siapkan fallback jika AI service down
- Jangan expose API key — Gunakan server-side calls, bukan client-side
Kesimpulan
Integrasi AI di Laravel membuka banyak peluang untuk fitur cerdas. Dari content generation hingga customer support otomatis, semua bisa dibangun dengan clean code dan arsitektur yang baik.