Module 2 – First OpenAI API call
Exercise
Exercise: first AI chat
Exercise: first AI chat
This lesson covers first AI chat in PHP in the context of PHP web apps using OpenAI and similar APIs. The focus is practical understanding of how the feature affects architecture, cost, and user experience in production.
Through the BrainTech AI Developer course you build modular integration from the first API call to RAG, agents, and local models. Examples use PHP 8, .env for secrets, and clear frontend/backend separation without exposing API keys to the client.
Task
- Create ai-lab/ in your PHP project with public/, src/, and config/.
- Add .env with OPENAI_API_KEY loaded via vlucas/phpdotenv or getenv().
- Implement AiClient service with chat(string $message): string.
- Build a simple HTML form and AJAX endpoint calling the service.
- Add error handling for HTTP 401, 429, and timeout — show user-friendly messages.
- Log each request: timestamp, model, estimated tokens, and duration in ms.
- Test with three different prompts and compare answers and cost.
- Optional: cache identical questions in Redis or file cache.
Goal: Successfully implement first AI chat in PHP in a PHP app with secure API calls and performance metrics.
