Introduction
Imagine an e-commerce site with thousands of products, managers spending 80% of their time on 'where is my order?' and 'how do I return?' questions, while customers leave due to slow responses. We faced this on a project where we implemented an AI chat on GPT-4o mini — response time dropped from 5 minutes to 5 seconds, and support load reduced by 70%. Integrating the OpenAI API solves such challenges: from chatbots to semantic catalog search. Our experience — over 5 years in development and over 30 AI projects on websites of various scales. Request a consultation — we'll analyze your case.
Problems We Solve
Support Overload
Every day — hundreds of identical questions. We configure GPT-4o mini with a system prompt based on your knowledge base. Result: the client receives an answer in seconds, a human only connects for complex cases. The cost of one request to GPT-4o mini is approximately $0.00015 (per 1000 tokens), allowing you to process thousands of requests for cents.
Complex Content Search
Regular full-text search does not understand synonyms and context. We implement semantic search via text-embedding-3-small and PostgreSQL with pgvector: search by meaning, not exact match. For example, the query 'how to connect WiFi' finds articles about router setup.
Manual Content Generation
Product descriptions, meta tags, news — writing them manually takes hours. DALL-E 3 creates images from text in seconds. We integrate generation directly into the CMS admin panel.
How We Do It
We use Laravel 11 on the backend and React 18 on the frontend. The OpenAI SDK for PHP handles requests to models. For streaming — Server-Sent Events.
Basic Chat Integration
use OpenAI\Client;
$openai = OpenAI::client(config('services.openai.api_key'));
$response = $openai->chat()->create([
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'system', 'content' => 'You are the support assistant of company X. Answer briefly and to the point.'],
['role' => 'user', 'content' => $userMessage],
],
'temperature' => 0.3,
'max_tokens' => 500,
]);
$answer = $response->choices[0]->message->content;
Streaming Responses (Server-Sent Events)
// PHP: server sends tokens as they are generated
Route::get('/api/chat/stream', function (Request $request) {
$message = $request->query('message');
return response()->stream(function () use ($message) {
$openai = OpenAI::client(config('services.openai.api_key'));
$stream = $openai->chat()->createStreamed([
'model' => 'gpt-4o-mini',
'messages' => [['role' => 'user', 'content' => $message]],
]);
foreach ($stream as $response) {
$chunk = $response->choices[0]->delta->content ?? '';
if ($chunk) {
echo "data: " . json_encode(['content' => $chunk]) . "\n\n";
ob_flush(); flush();
}
}
echo "data: [DONE]\n\n";
}, 200, [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
]);
});
// TypeScript: client reads SSE stream and displays text gradually
async function streamChat(message: string, onChunk: (text: string) => void) {
const resp = await fetch(`/api/chat/stream?message=${encodeURIComponent(message)}`);
const reader = resp.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const lines = decoder.decode(value).split('\n');
for (const line of lines) {
if (line.startsWith('data: ') && line !== 'data: [DONE]') {
const data = JSON.parse(line.slice(6));
onChunk(data.content);
}
}
}
}
Embeddings for Semantic Search
// Indexing content
$response = $openai->embeddings()->create([
'model' => 'text-embedding-3-small',
'input' => $article->title . "\n" . $article->content,
]);
$embedding = $response->embeddings[0]->embedding; // vector 1536 dimensions
// Save to PostgreSQL with pgvector
DB::statement('UPDATE articles SET embedding = ? WHERE id = ?', [json_encode($embedding), $article->id]);
// Search by vector similarity
$queryEmbedding = getEmbedding($searchQuery); // your method for getting embeddings
$results = DB::select(
'SELECT *, (embedding <=> ?) AS distance FROM articles ORDER BY distance LIMIT 5',
[json_encode($queryEmbedding)]
);
Content Moderation
$moderation = $openai->moderations()->create([
'input' => $userComment,
]);
if ($moderation->results[0]->flagged) {
throw new ContentModerationException('Comment violates site rules');
}
Model Comparison: GPT-4o mini vs GPT-4o
| Characteristic | GPT-4o mini | GPT-4o |
|---|---|---|
| Response speed | up to 100 tokens/s | up to 50 tokens/s |
| Quality (MMLU) | 87% | 88.7% |
| Cost | 20 times cheaper | — |
| Max tokens | 128K | 128K |
| Best use | Chatbots, fast answers | Analytics, complex reasoning |
GPT-4o mini is 20 times cheaper with nearly the same quality. For 90% of tasks, it is sufficient.
Why Streaming Improves User Experience?
The user expects a response within 2 seconds. Full text generation takes 5-15 seconds. Streaming sends tokens as they appear — the live typing effect reduces perceived latency. We implement SSE as in the example above, and the UI displays text gradually.
How to Choose a Model for a Chatbot?
If you need a fast and cheap chat — choose GPT-4o mini (temperature 0.3-0.5, up to 500 tokens). If the dialogue requires context analysis or translation — GPT-4o. For semantic search, use text-embedding-3-small — it generates a vector in 200 ms.
What's Included
- Documentation on integration and prompt structure
- Access to the code repository (GitLab/GitHub)
- Team training on working with AI features
- Technical support for 30 days after launch
- Monitoring and dashboards of key metrics
Integration Stages
- Audit of the current site architecture, analysis of the knowledge base.
- Design of BFF (Backend For Frontend) for secure API calls.
- Implementation of a middleware layer with caching and rate limits.
- Writing and testing prompts for your scenarios.
- Integration with the chosen CMS (Laravel, WordPress, Drupal, etc.).
- Monitoring and iterative improvement of response quality.
Key Monitoring Metrics
| Metric | Target Value | Description |
|---|---|---|
| Response time (p95) | < 2 s | Generation time + network latency |
| Resolution rate | > 85% | Percentage of questions answered by AI without escalation |
| Cost per 1000 requests | — | Controlled via max_tokens and caching |
Common Mistakes and How to Avoid Them
- OpenAI recommends trimming dialog history to 10-20 messages to avoid exceeding token limits.
- N+1 queries: each API call costs money. Cache frequent answers (Redis, Cache).
- Context leakage: the system prompt is lost on restart. Add it to each request.
- Ignoring moderation: without it, the site risks toxic content. Enable the moderation endpoint.
Full Integration Checklist
- [ ] Check OpenAI rate limits
- [ ] Set up error monitoring (Sentry, Logstash)
- [ ] Test streaming in different browsers
- [ ] Conduct load testing of the chat
- [ ] Update privacy policy
Timeframes and Cost
Estimated timeframes:
- AI chat with streaming: 3–4 days
- Semantic search with pgvector: +2 days
- DALL-E 3 image generation: 1–2 days
The cost is calculated individually for your project. Support savings after implementation can reach 70% of monthly costs. Contact us for a preliminary estimate and a demonstration on your data. We will analyze the task and offer the optimal turnkey architecture. No fluff, only working code and support at all stages.
Ready to start? Request a consultation — we'll discuss the details of your project.







