Building the Chat Manager

Welcome back! In the previous lesson, we explored the importance of a robust system prompt and how it guides the behavior of our chatbot. Now, we will delve into the next step of our journey: building the chat manager. This lesson will focus on the model layer of the MVC (model-view-controller) architecture, which is crucial for organizing and managing data in a structured way. The ChatManager class will be the core component of our model layer, responsible for managing chat data effectively. By the end of this lesson, you will understand how to create, manage, and retrieve chat data using the ChatManager class.

Initializing the ChatManager

The ChatManager class is designed to handle the storage and management of chat data. It serves as the backbone of our chatbot's data management system. We'll start by setting up the class and then gradually add methods to handle chat creation, message addition, and conversation retrieval.

Let's begin by defining the ChatManager class and its constructor. The constructor initializes an empty array, $this->chats, which will store all chat data.

In this setup, $this->chats is a nested associative array where the first key is the user_id, and the second key is the chat_id. This structure allows us to efficiently manage multiple chats for different users.

💡 Note: The in-memory array $this->chats is intended for local development, testing and teaching purposes only. While it provides a simple and effective way to manage chat data during development, it is not suitable for production use. For a complete solution, you would replace this with a more robust storage mechanism such as a database to ensure data persistence and scalability.

Creating a New Chat

Next, we'll add the createChat method. This method is responsible for creating a new chat entry for a user. It takes three parameters: userId, chatId, and systemPrompt.

The createChat method checks if the userId exists in $this->chats. If not, it creates a new entry. Then, it initializes the chat with the provided systemPrompt and an empty array for messages.

Retrieving a Chat

To access a specific chat, we need the getChat method. This method retrieves a chat based on the userId and chatId.

The getChat method uses the null coalescing operator to safely access the nested array, returning the chat data if it exists.

Adding Messages to a Chat

Now, let's add the addMessage method. This method allows us to append messages to a chat. It requires the userId, chatId, role, and content of the message.

The addMessage method first checks if the chat exists using isset. If the chat exists, it appends the message to the chat's message array.

Retrieving the Full Conversation

Finally, we'll implement the getConversation method. This method returns the entire conversation, including the system prompt and all messages.

The getConversation method retrieves the chat and constructs an array starting with the system prompt, followed by the chat messages. If the chat does not exist, it returns an empty array.

Creating and Managing Chats

To create a new chat, we use the createChat method. This method takes three parameters: userId, chatId, and systemPrompt. It initializes a new chat entry in the $this->chats array. If the userId does not already exist in the array, a new entry is created. The chat entry includes the system prompt and an empty array for messages.

Here's an example of how to create a new chat:

In this example, we initialize a ChatManager instance and create a new chat for a user with the ID "user123". The chat is identified by "chat123" and is initialized with a system prompt. This setup allows us to manage chat data efficiently.

💡 Note: The base prompt is stored separately from the messages to ensure clarity and consistency throughout the conversation. By keeping the prompt as a distinct property rather than embedding it within the message list, we can easily retrieve and modify the system's initial instructions without interfering with the user's messages. This separation also allows us to apply the same prompt across multiple conversations, making the architecture more flexible and scalable.

Adding and Retrieving Messages

Once a chat is created, we can add messages to it using the addMessage method. This method requires the userId, chatId, role, and content of the message. The role indicates whether the message is from the user or the assistant. The message is then appended to the chat's message array.

Here's how you can add messages to a chat:

In this example, we add a user message, "Hello!", and an assistant response, "Hi there!", to the chat. The addMessage method ensures that messages are stored in the correct chat entry.

Retrieving Conversation

To retrieve the entire conversation, including the system prompt, we use the getConversation method. This method returns an array of messages, starting with the system prompt followed by the chat messages.

The getConversation method compiles the chat history, allowing us to access the full context of the conversation.

Summary and Preparation for Practice

In this lesson, we explored the ChatManager class and its role in managing chat data within the model layer of our application. We learned how to create and manage chats, add messages, and retrieve chat histories. The ChatManager is a crucial component for organizing chat data, ensuring that our chatbot can handle multiple conversations efficiently.

As you move on to the practice exercises, take the opportunity to experiment with modifying and extending the ChatManager 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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal