Sebelum memulai praktik, pastikan Anda telah memahami konsep dasar pada materi kelas AI Agent & PHP di infokoding.

BAB 21

Studi Kasus Nyata: Membangun AI Agent Lengkap

Implementasi nyata AI Agent PHP end-to-end: menjawab pertanyaan, query database MySQL, membaca file PDF, integrasi API eksternal, MCP tools, dan persistent memory.

Terakhir diperbarui:

Skenario Studi Kasus

Kita membangun AI Agent Customer Support untuk perusahaan e-commerce yang mampu:

  • Menjawab pertanyaan umum tentang produk dan layanan
  • Mencari data pesanan dan user dari database MySQL
  • Membaca panduan produk dari file PDF
  • Mengecek status pengiriman via Shipping API eksternal
  • Mengingat percakapan antar session user

Arsitektur Solusi

User Request
    │
    ▼
[API Endpoint] ──→ [Auth + Rate Limit]
    │
    ▼
[CustomerSupportAgent]
    │
    ├── [Memory: DatabaseMemory] ──→ MySQL (chat_messages)
    │
    ├── [MCP Client]
    │       ├── [DatabaseTool]   ──→ searchOrder(), searchUser()
    │       ├── [FileTool]       ──→ readPDF("product-guide.pdf")
    │       ├── [ShippingTool]   ──→ trackPackage(trackingNumber)
    │       └── [CalculatorTool] ──→ calculate(operation, a, b)
    │
    └── [OpenAI GPT-4o-mini]
            └── Response → User

Implementasi CustomerSupportAgent

<?php

namespace App\Agent;

use App\OpenAIClient;
use App\MCP\McpClient;
use App\Logger\Logger;

class CustomerSupportAgent
{
    private OpenAIClient $client;
    private McpClient $mcpClient;
    private Logger $logger;
    private array $messages = [];
    private int $maxIterations;

    public function __construct(
        OpenAIClient $client,
        McpClient $mcpClient,
        Logger $logger,
        int $maxIterations = 8
    ) {
        $this->client        = $client;
        $this->mcpClient     = $mcpClient;
        $this->logger        = $logger;
        $this->maxIterations = $maxIterations;
    }

    public function handle(string $userId, string $userMessage, array $history = []): array
    {
        $startTime = microtime(true);
        $toolsUsed = [];

        // Build messages dengan history
        $this->messages = array_merge(
            [['role' => 'system', 'content' => $this->getSystemPrompt()]],
            $history,
            [['role' => 'user', 'content' => $userMessage]]
        );

        $toolDefs = $this->mcpClient->getToolDefinitions();
        $answer   = '';

        for ($i = 0; $i < $this->maxIterations; $i++) {
            $response = $this->client->chat($this->messages, $toolDefs);
            $message  = $response['choices'][0]['message'];
            $this->messages[] = $message;

            if (!empty($message['tool_calls'])) {
                foreach ($message['tool_calls'] as $toolCall) {
                    $name        = $toolCall['function']['name'];
                    $toolsUsed[] = $name;
                    $this->logger->info("Tool dipanggil", ['tool' => $name, 'user' => $userId]);

                    $result           = $this->mcpClient->executeToolCall($toolCall);
                    $this->messages[] = $result;
                }
                continue;
            }

            $answer = $message['content'] ?? '';
            break;
        }

        $durationMs = (int) ((microtime(true) - $startTime) * 1000);

        return [
            'answer'       => $answer,
            'tools_used'   => $toolsUsed,
            'duration_ms'  => $durationMs,
            'token_usage'  => $response['usage'] ?? [],
        ];
    }

    private function getSystemPrompt(): string
    {
        return <<

Entry Point Aplikasi

<?php
// api/chat.php
require_once __DIR__ . '/../vendor/autoload.php';

$config = require __DIR__ . '/../config/config.php';
$input  = json_decode(file_get_contents('php://input'), true);

// Validasi input
$message = htmlspecialchars(trim($input['message'] ?? ''), ENT_QUOTES, 'UTF-8');
if (empty($message) || strlen($message) > 2000) {
    http_response_code(400);
    echo json_encode(['error' => 'Pesan tidak valid']);
    exit;
}

// Setup
$pdo      = new PDO("mysql:host={$config['db']['host']};dbname={$config['db']['name']}", ...);
$memory   = new App\Memory\DatabaseMemory($pdo, session_id());
$history  = $memory->getAll(limit: 20);

$client   = new App\OpenAIClient($config['openai_api_key']);
$logger   = new App\Logger\Logger('./logs/agent.log', 'info');

$mcpServer = new App\MCP\McpServer();
$mcpServer
    ->register('database_query', new App\Tools\DatabaseTool($pdo))
    ->register('read_file', new App\Tools\FileTool('./uploads'))
    ->register('calculate', new App\Tools\CalculatorTool());

$mcpClient = new App\MCP\McpClient($mcpServer);
$agent     = new App\Agent\CustomerSupportAgent($client, $mcpClient, $logger);

// Proses pesan
$result = $agent->handle(session_id(), $message, $history);

// Simpan ke memory
$memory->add('user', $message);
$memory->add('assistant', $result['answer']);

echo json_encode([
    'answer'    => $result['answer'],
    'tools_used' => $result['tools_used'],
]);

Poin Kunci Bab 21

Studi kasus ini menggabungkan semua konsep yang telah kita pelajari: Agent, Tools, MCP, Memory, Logging, dan Authentication. Ini adalah blueprint yang bisa langsung Anda adaptasi untuk kebutuhan bisnis nyata.