Hello!

BrainTech - software solutions, web design and applications.

Contact

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

  1. Create ai-lab/ in your PHP project with public/, src/, and config/.
  2. Add .env with OPENAI_API_KEY loaded via vlucas/phpdotenv or getenv().
  3. Implement AiClient service with chat(string $message): string.
  4. Build a simple HTML form and AJAX endpoint calling the service.
  5. Add error handling for HTTP 401, 429, and timeout — show user-friendly messages.
  6. Log each request: timestamp, model, estimated tokens, and duration in ms.
  7. Test with three different prompts and compare answers and cost.
  8. 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.

Design Wireframe
High Fidelity Design
Design development
Design development
Design development
Research development