AI integration transforms application capabilities. OpenAI GPT enables intelligent content generation, chat, and analysis. At ZIRA Software, we integrate AI features that enhance user experiences across platforms.
Installation
composer require openai-php/laravel
php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"
# .env
OPENAI_API_KEY=sk-...
OPENAI_ORGANIZATION=org-...
Basic Chat Completion
use OpenAI\Laravel\Facades\OpenAI;
class AIService
{
public function chat(string $message): string
{
$response = OpenAI::chat()->create([
'model' => 'gpt-4',
'messages' => [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => $message],
],
'max_tokens' => 1000,
]);
return $response->choices[0]->message->content;
}
}
Conversational Memory
// app/Services/ConversationService.php
class ConversationService
{
public function chat(Conversation $conversation, string $message): string
{
// Build message history
$messages = [
['role' => 'system', 'content' => $conversation->system_prompt],
];
foreach ($conversation->messages as $msg) {
$messages[] = [
'role' => $msg->role,
'content' => $msg->content,
];
}
$messages[] = ['role' => 'user', 'content' => $message];
// Get AI response
$response = OpenAI::chat()->create([
'model' => 'gpt-4',
'messages' => $messages,
'max_tokens' => 1000,
]);
$aiResponse = $response->choices[0]->message->content;
// Store messages
$conversation->messages()->createMany([
['role' => 'user', 'content' => $message],
['role' => 'assistant', 'content' => $aiResponse],
]);
return $aiResponse;
}
}
Content Generation
// app/Services/ContentGenerator.php
class ContentGenerator
{
public function generateBlogPost(string $topic, string $tone = 'professional'): array
{
$response = OpenAI::chat()->create([
'model' => 'gpt-4',
'messages' => [
[
'role' => 'system',
'content' => "You are a content writer. Write in a {$tone} tone.
Return JSON with 'title', 'excerpt', and 'content' keys.",
],
[
'role' => 'user',
'content' => "Write a blog post about: {$topic}",
],
],
'response_format' => ['type' => 'json_object'],
]);
return json_decode($response->choices[0]->message->content, true);
}
public function generateProductDescription(Product $product): string
{
$response = OpenAI::chat()->create([
'model' => 'gpt-4',
'messages' => [
[
'role' => 'system',
'content' => 'Write compelling product descriptions for e-commerce.',
],
[
'role' => 'user',
'content' => "Product: {$product->name}\n" .
"Category: {$product->category->name}\n" .
"Features: " . implode(', ', $product->features),
],
],
]);
return $response->choices[0]->message->content;
}
}
Embeddings for Search
// app/Services/SemanticSearch.php
class SemanticSearch
{
public function generateEmbedding(string $text): array
{
$response = OpenAI::embeddings()->create([
'model' => 'text-embedding-ada-002',
'input' => $text,
]);
return $response->embeddings[0]->embedding;
}
public function indexDocument(Document $document): void
{
$embedding = $this->generateEmbedding($document->content);
$document->update([
'embedding' => json_encode($embedding),
]);
}
public function search(string $query, int $limit = 10): Collection
{
$queryEmbedding = $this->generateEmbedding($query);
// Using PostgreSQL pgvector
return Document::orderByRaw(
'embedding <-> ?::vector',
[json_encode($queryEmbedding)]
)->limit($limit)->get();
}
}
Streaming Responses
// app/Http/Controllers/ChatController.php
class ChatController extends Controller
{
public function stream(Request $request)
{
return response()->stream(function () use ($request) {
$stream = OpenAI::chat()->createStreamed([
'model' => 'gpt-4',
'messages' => [
['role' => 'user', 'content' => $request->message],
],
]);
foreach ($stream as $response) {
$content = $response->choices[0]->delta->content ?? '';
if ($content) {
echo "data: " . json_encode(['content' => $content]) . "\n\n";
ob_flush();
flush();
}
}
echo "data: [DONE]\n\n";
}, 200, [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
'Connection' => 'keep-alive',
]);
}
}
Function Calling
// app/Services/AIAssistant.php
class AIAssistant
{
public function handleQuery(string $query): mixed
{
$response = OpenAI::chat()->create([
'model' => 'gpt-4',
'messages' => [
['role' => 'user', 'content' => $query],
],
'functions' => [
[
'name' => 'get_order_status',
'description' => 'Get the status of an order by order ID',
'parameters' => [
'type' => 'object',
'properties' => [
'order_id' => [
'type' => 'string',
'description' => 'The order ID',
],
],
'required' => ['order_id'],
],
],
[
'name' => 'search_products',
'description' => 'Search for products',
'parameters' => [
'type' => 'object',
'properties' => [
'query' => ['type' => 'string'],
'category' => ['type' => 'string'],
],
],
],
],
]);
$message = $response->choices[0]->message;
if ($message->functionCall) {
return $this->executeFunction(
$message->functionCall->name,
json_decode($message->functionCall->arguments, true)
);
}
return $message->content;
}
private function executeFunction(string $name, array $args): mixed
{
return match ($name) {
'get_order_status' => Order::find($args['order_id'])?->status,
'search_products' => Product::search($args['query'])->get(),
default => null,
};
}
}
Rate Limiting and Caching
// app/Services/AIService.php
class AIService
{
public function cachedCompletion(string $prompt, int $ttl = 3600): string
{
$cacheKey = 'ai:' . md5($prompt);
return Cache::remember($cacheKey, $ttl, function () use ($prompt) {
return $this->complete($prompt);
});
}
}
// Rate limiting in controller
public function chat(Request $request)
{
$key = 'ai-requests:' . auth()->id();
if (RateLimiter::tooManyAttempts($key, 10)) {
return response()->json(['error' => 'Too many requests'], 429);
}
RateLimiter::hit($key, 60);
// Process request...
}
Conclusion
OpenAI GPT integration adds powerful AI capabilities to Laravel applications. From content generation to intelligent search, AI features enhance user experiences significantly.
Building AI-powered features? Contact ZIRA Software for AI integration services.