AI-powered support reduces response times and scales customer service. GPT-4 with Laravel creates intelligent, context-aware support systems. At ZIRA Software, our AI support implementations handle 70% of inquiries automatically.
System Architecture
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Customer UI │────▶│ Laravel API │────▶│ OpenAI GPT-4 │
└─────────────────┘ └────────┬────────┘ └─────────────────┘
│
┌────────────┼────────────┐
│ │ │
▼ ▼ ▼
Knowledge Conversation Escalation
Base History Queue
Database Schema
Schema::create('conversations', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_id')->constrained('users');
$table->foreignId('assigned_agent_id')->nullable()->constrained('users');
$table->string('channel')->default('web'); // web, email, api
$table->string('status')->default('active'); // active, resolved, escalated
$table->string('subject')->nullable();
$table->integer('ai_confidence_score')->nullable();
$table->boolean('requires_human')->default(false);
$table->timestamps();
});
Schema::create('messages', function (Blueprint $table) {
$table->id();
$table->foreignId('conversation_id')->constrained()->onDelete('cascade');
$table->enum('role', ['user', 'assistant', 'system', 'agent']);
$table->text('content');
$table->json('metadata')->nullable();
$table->integer('tokens_used')->nullable();
$table->timestamps();
});
Schema::create('knowledge_articles', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->string('category');
$table->json('tags')->nullable();
$table->vector('embedding', 1536)->nullable(); // pgvector
$table->boolean('active')->default(true);
$table->timestamps();
});
AI Support Service
// app/Services/AISupportService.php
class AISupportService
{
public function __construct(
private KnowledgeBaseService $knowledge,
private EscalationService $escalation,
) {}
public function handleMessage(Conversation $conversation, string $message): Message
{
// Store user message
$userMessage = $conversation->messages()->create([
'role' => 'user',
'content' => $message,
]);
// Get relevant knowledge
$context = $this->knowledge->getRelevantArticles($message);
// Build conversation history
$messages = $this->buildMessages($conversation, $context);
// Get AI response
$response = OpenAI::chat()->create([
'model' => 'gpt-4-turbo-preview',
'messages' => $messages,
'functions' => $this->getFunctions(),
'temperature' => 0.7,
'max_tokens' => 1000,
]);
$aiMessage = $response->choices[0]->message;
// Handle function calls (escalation, etc.)
if ($aiMessage->functionCall) {
return $this->handleFunctionCall($conversation, $aiMessage);
}
// Store AI response
return $conversation->messages()->create([
'role' => 'assistant',
'content' => $aiMessage->content,
'metadata' => [
'model' => 'gpt-4-turbo-preview',
'tokens' => $response->usage->totalTokens,
],
]);
}
private function buildMessages(Conversation $conversation, Collection $context): array
{
$systemPrompt = <<<PROMPT
You are a helpful customer support assistant for {$this->getCompanyName()}.
Use the following knowledge base articles to help answer questions:
{$context->pluck('content')->join("\n\n---\n\n")}
Guidelines:
- Be friendly, professional, and concise
- If you cannot answer confidently, use the escalate_to_human function
- Never make up information about products, pricing, or policies
- Ask clarifying questions if needed
If the customer seems frustrated or the issue is complex, escalate to a human agent.
PROMPT;
$messages = [
['role' => 'system', 'content' => $systemPrompt],
];
// Add conversation history (last 10 messages)
foreach ($conversation->messages()->latest()->take(10)->get()->reverse() as $msg) {
$messages[] = [
'role' => $msg->role === 'agent' ? 'assistant' : $msg->role,
'content' => $msg->content,
];
}
return $messages;
}
private function getFunctions(): array
{
return [
[
'name' => 'escalate_to_human',
'description' => 'Escalate the conversation to a human agent',
'parameters' => [
'type' => 'object',
'properties' => [
'reason' => [
'type' => 'string',
'description' => 'Why escalation is needed',
],
'priority' => [
'type' => 'string',
'enum' => ['low', 'medium', 'high'],
],
],
'required' => ['reason'],
],
],
[
'name' => 'create_ticket',
'description' => 'Create a support ticket for follow-up',
'parameters' => [
'type' => 'object',
'properties' => [
'subject' => ['type' => 'string'],
'category' => ['type' => 'string'],
],
'required' => ['subject'],
],
],
];
}
}
Knowledge Base with Embeddings
// app/Services/KnowledgeBaseService.php
class KnowledgeBaseService
{
public function getRelevantArticles(string $query, int $limit = 3): Collection
{
$queryEmbedding = $this->generateEmbedding($query);
return KnowledgeArticle::query()
->where('active', true)
->orderByRaw('embedding <-> ?::vector', [json_encode($queryEmbedding)])
->limit($limit)
->get();
}
public function indexArticle(KnowledgeArticle $article): void
{
$embedding = $this->generateEmbedding(
$article->title . "\n\n" . $article->content
);
$article->update(['embedding' => $embedding]);
}
private function generateEmbedding(string $text): array
{
$response = OpenAI::embeddings()->create([
'model' => 'text-embedding-3-small',
'input' => $text,
]);
return $response->embeddings[0]->embedding;
}
}
Escalation Service
// app/Services/EscalationService.php
class EscalationService
{
public function escalate(Conversation $conversation, string $reason, string $priority = 'medium'): void
{
$conversation->update([
'status' => 'escalated',
'requires_human' => true,
]);
$conversation->messages()->create([
'role' => 'system',
'content' => "Escalated to human agent. Reason: {$reason}",
'metadata' => ['priority' => $priority],
]);
// Notify available agents
event(new ConversationEscalated($conversation, $reason, $priority));
// Auto-assign if agents available
$this->autoAssign($conversation, $priority);
}
private function autoAssign(Conversation $conversation, string $priority): void
{
$agent = User::role('support_agent')
->where('is_available', true)
->withCount(['assignedConversations' => fn($q) => $q->where('status', 'active')])
->orderBy('assigned_conversations_count')
->first();
if ($agent) {
$conversation->update(['assigned_agent_id' => $agent->id]);
$agent->notify(new NewConversationAssigned($conversation));
}
}
}
Conclusion
AI customer support with Laravel and GPT-4 automates routine inquiries while seamlessly escalating complex issues to human agents. Knowledge base integration ensures accurate, helpful responses.
Building AI support systems? Contact ZIRA Software for intelligent chatbot development.