In the previous lesson, we explored the ChatManager
class, which plays a crucial role in managing chat data within our application. Now, we will take the next step in our journey by building the chat service layer. This layer is essential for integrating the language model with chat sessions, allowing us to process user messages and generate AI responses. By the end of this lesson, you will understand how to set up the ChatService
class, create chat sessions, and process messages using OpenAI's PHP client.
The service layer acts as a bridge between the model layer, where data is managed, and the AI model, which generates responses. It is responsible for orchestrating the flow of data and ensuring that user interactions are handled smoothly. Let's dive into the details of setting up this important component.
The ChatService
class is the heart of our service layer. It is responsible for managing chat sessions and interacting with OpenAI’s API to generate AI responses. To begin, we need to set up the class and its components.
First, we import the necessary classes, including the ChatManager
from our previous lesson and OpenAI's PHP client. Here's how the class is initialized:
php1<?php 2 3namespace App\Services; 4 5use App\Models\ChatManager; 6use OpenAI; 7 8class ChatService { 9 private ChatManager $chatManager; 10 private OpenAI\Client $openai; 11 private string $systemPrompt; 12 13 public function __construct() { 14 $this->chatManager = new ChatManager(); 15 16 // Load OpenAI API key from environment variables 17 $apiKey = $_ENV['OPENAI_API_KEY'] ?? getenv('OPENAI_API_KEY'); 18 $baseUrl = $_ENV['OPENAI_BASE_URI'] ?? getenv('OPENAI_BASE_URI'); 19 20 // Initialize the OpenAI client 21 $this->openai = OpenAI::factory() 22 ->withApiKey($apiKey) 23 ->withBaseUri($baseUrl) 24 ->make(); 25 26 $this->systemPrompt = $this->loadSystemPrompt(__DIR__ . '/../data/system_prompt.txt'); 27 } 28}
In this setup, we instantiate ChatManager
to manage chat data, initialize the OpenAI client, and load the systemPrompt
using the loadSystemPrompt
method.
The system prompt is a crucial component that guides the AI’s responses. It provides context and instructions for the AI, ensuring that it behaves in a manner consistent with our application's goals. Here’s how we implement the loadSystemPrompt
method:
php1private function loadSystemPrompt(string $filePath): string { 2 return file_exists($filePath) ? file_get_contents($filePath) : "You are a helpful assistant."; 3}
This method attempts to read the system prompt from a specified file path. If successful, it returns the prompt as a string. In case of an error, it prints an error message and returns a default prompt. This ensures that the application can continue functioning even if the file is missing or corrupted.
Creating a new chat session is a fundamental task of the ChatService
. The createChat
method is responsible for generating a unique chat ID and initializing a chat session using the ChatManager
.
php1public function createChat($userId) { 2 $chatId = uniqid(); 3 $this->chatManager->createChat($userId, $chatId, $this->systemPrompt); 4 return $chatId; 5}
In this method, we generate a unique chatId
using PHP's uniqid()
function. We then call the createChat
method of ChatManager
, passing the userId
, chatId
, and systemPrompt
. This initializes a new chat session, which is ready to receive messages.
he processMessage
method is where the magic happens. It processes user messages, interacts with the OpenAI client to generate responses, and updates the chat history. Below, we outline the steps involved in this process, followed by the corresponding code implementation:
- Retrieve the chat using
getChat
, and raise an error if the chat is not found. - Add the user's message to the chat history.
- Send the conversation, including the system prompt and all messages, to the AI client to generate a response.
- Add the AI's response to the chat history and return it to the user.
- Handle any errors with the AI client gracefully.
php1public function processMessage($userId, $chatId, $message) { 2 // Retrieve the chat 3 $chat = $this->chatManager->getChat($userId, $chatId); 4 if (!$chat) { 5 throw new \Exception("Chat not found"); 6 } 7 8 // Add user message to chat history 9 $this->chatManager->addMessage($userId, $chatId, "user", $message); 10 11 try { 12 // Get AI response from OpenAI 13 $conversation = $this->chatManager->getConversation($userId, $chatId); 14 15 $response = $this->openai->chat()->create([ 16 'model' => 'gpt-4', 17 'messages' => $conversation, 18 ]); 19 20 $aiMessage = $response['choices'][0]['message']['content'] ?? "I'm sorry, I couldn't generate a response."; 21 22 // Add AI response to chat history 23 $this->chatManager->addMessage($userId, $chatId, "assistant", $aiMessage); 24 25 return $aiMessage; 26 } catch (\Exception $e) { 27 throw new \RuntimeException("Error getting AI response: " . $e->getMessage()); 28 } 29}
In the context of a customer service agent, we configure our model with specific parameters to optimize its performance. The OpenAI client is assumed to handle these configurations internally, ensuring responses are both engaging and relevant.
Let's see the ChatService
in action by simulating a chat session. We'll use a PHP script to create a chat session and process a user message.
php1<?php 2 3require 'vendor/autoload.php'; 4 5use App\Services\ChatService; 6 7// Initialize the chat service 8$chatService = new ChatService(); 9 10// Simulate a user ID 11$userId = "user123"; 12 13// Create a new chat session 14$chatId = $chatService->createChat($userId); 15echo "Chat session created with ID: $chatId\n"; 16 17// Simulate sending a message 18$userMessage = "Hello, how are you?"; 19 20try { 21 $aiResponse = $chatService->processMessage($userId, $chatId, $userMessage); 22 echo "AI Response: $aiResponse\n"; 23} catch (Exception $e) { 24 echo "Error: " . $e->getMessage() . "\n"; 25}
In this example, we initialize the ChatService
, simulate a user ID, and create a new chat session, printing the chat ID. We then simulate sending a message and print the AI's response, demonstrating the flow from user input to AI response and showcasing the functionality of the ChatService
.
Plain text1Chat session created with ID: 01a178708a4f4b6fa3cef04e1136d597 2AI Response: Hello! I'm here to help with any questions or concerns you might have regarding our IT services. How can I assist you today?
This output illustrates a successful interaction where a new chat session is created, and the AI responds to the user's greeting with a helpful message. The AI's response is tailored to assist with IT services, showcasing the system's ability to provide relevant and context-aware assistance.
In this lesson, we explored the ChatService
class and its role in integrating OpenAI's language model with chat sessions. We learned how to set up the class, load the system prompt, create chat sessions, and process user messages. The service layer is a vital component of our chatbot application, ensuring that user interactions are handled smoothly and efficiently.
As you move on to the practice exercises, take the opportunity to experiment with the ChatService
functionality. This hands-on practice will reinforce the concepts covered in this lesson and prepare you for the next steps in our course. Keep up the great work, and I look forward to seeing your progress!