Managing Multiple Chat Sessions with OpenAI in PHP
Managing Multiple Chat Sessions with OpenAI
Welcome to the next step in your journey of creating a chatbot with OpenAI! In the previous lessons, you learned how to send messages to OpenAI's language model, explored model parameters, maintained conversation history, and personalized AI behavior with system prompts. Now, we will focus on managing multiple chat sessions. This is crucial for applications where you need to handle several conversations simultaneously, such as customer service chatbots. By the end of this lesson, you will be able to create and manage multiple chat sessions using OpenAI's API, setting the stage for more complex interactions.
Production Note
This unit uses global arrays like $chatSessions to demonstrate how separate conversations can be tracked. That is fine for a teaching example, but production code should usually encapsulate session state in a class or persistent store and avoid depending on mutable global state.
For the same reason, uniqid() is acceptable here as a simple demo tool, but production systems should prefer stronger identifiers such as:
PHP
$chatId = bin2hex(random_bytes(16));
Also avoid logging full conversation histories in production unless you have a clear need and appropriate safeguards for sensitive user data.
Creating Unique Chat Sessions
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
In a chatbot application, each conversation should be treated as a separate session. To achieve this, we use unique identifiers for each chat session. This ensures that messages and responses are correctly associated with their respective sessions. In our code example, we use PHP's uniqid() function to generate a unique identifier for each chat session. When a new chat session is created, a unique chat_id is generated, and an empty conversation history is initialized.
PHP
require 'vendor/autoload.php';// Fetch the api key$apiKey = $_ENV['OPENAI_API_KEY'] ?? getenv('OPENAI_API_KEY');$baseUrl = $_ENV['OPENAI_BASE_URL'] ?? getenv('OPENAI_BASE_URL');$baseUrl = rtrim($baseUrl, '/');if (!str_ends_with($baseUrl, '/v1')) { $baseUrl .= '/v1';}// Initialize the OpenAI client$client = \OpenAI::factory() ->withApiKey($apiKey) ->withBaseUri($baseUrl) ->make();// Store all active chat sessions$chat_sessions = [];// Define a common system prompt for all conversations$system_prompt = [ "role" => "system", "content" => "You are a friendly and efficient customer service attendant eager to assist customers with their inquiries and concerns."];// Create a new chat session with a unique identifierfunction create_chat() { global $chat_sessions, $system_prompt; $chat_id = uniqid(); // Create unique session identifier $chat_sessions[$chat_id] = []; // Initialize empty conversation history $chat_sessions[$chat_id][] = $system_prompt; // Add system prompt to conversation history return $chat_id;}
In our example, we store conversation history in an associative array called $chat_sessions, where each key is a unique chat_id. When a user sends a message, it is added to the conversation history, ensuring that the AI has access to the full context when generating a response. This approach helps create a seamless and coherent interaction between the user and the AI.
Sending Messages and Receiving Responses
Handling Multiple Chat Sessions
Managing multiple chat sessions simultaneously is a crucial feature for advanced chatbot applications. By using unique identifiers, you can create and interact with different chat sessions independently, ensuring that each conversation remains distinct and contextually accurate. Below, we demonstrate this by initiating a first session and sending messages to it.
<?php// Create the first chat and send messages$chat_id1 = create_chat();echo "Chat 1, First Message: " . send_message($chat_id1, "I'm having trouble with my recent order. Can you help me track it?") . "\n";echo "Chat 1, Follow-up Message: " . send_message($chat_id1, "It was supposed to arrive yesterday but hasn't. What should I do next?") . "\n";?>
Output for the first chat session:
Chat 1, First Message: Sure, I can help with that. Could you please provide your order number?Chat 1, Follow-up Message: I recommend checking with the delivery service for any updates. If there's no information, please contact our support team for further assistance.
Now, let's create a second chat session and interact with it.
<?php// Create the second chat and send messages$chat_id2 = create_chat();echo "Chat 2, First Message: " . send_message($chat_id2, "I'm interested in upgrading my membership. What are the benefits?") . "\n";echo "Chat 2, Follow-up Message: " . send_message($chat_id2, "Could you guide me through the upgrade process?") . "\n";?>
Output for the second chat session:
Chat 2, First Message: Upgrading your membership offers benefits such as exclusive discounts, early access to new features, and priority customer support.Chat 2, Follow-up Message: Certainly! To upgrade, please visit your account settings and select the 'Upgrade Membership' option. Follow the prompts to complete the process.
This approach not only maintains the integrity of each conversation but also enhances scalability, making it ideal for applications like customer support where multiple interactions occur simultaneously. By keeping conversations separate, you can provide a more efficient and effective service to each user.
Summary and Preparation for Practice
In this lesson, you learned how to manage multiple chat sessions using OpenAI's API. We covered creating unique chat sessions, maintaining conversation history, and handling multiple interactions simultaneously. These skills are essential for building scalable chatbot applications that can handle numerous conversations at once. As you move on to the practice exercises, I encourage you to apply what you've learned by creating and managing chat sessions independently. This hands-on practice will reinforce your understanding and prepare you for more advanced chatbot development. Keep up the great work, and enjoy the journey of creating your chatbot with OpenAI!
Once a chat session is established, you can send messages and receive responses from the OpenAI model. It's important to maintain the context by sending the full conversation history to the model. In our code example, we use the send_message function to handle this process. The function takes a chat_id and a user_message as inputs, adds the message to the conversation history, and requests a response from the AI. The response is then processed and added to the conversation history, ensuring continuity in the interaction.
PHP
function send_message($chat_id, $user_message) { global $chat_sessions, $client; // Verify chat session exists if (!isset($chat_sessions[$chat_id])) { throw new Exception("Chat session not found!"); } // Add user's message to history $chat_sessions[$chat_id][] = ["role" => "user", "content" => $user_message]; // Create a chat request to get the AI response $response = $client->chat()->create([ 'model' => 'gpt-6-luna', 'messages' => $chat_sessions[$chat_id] ]); // Extract the AI's response from the API result $answer = trim($response->choices[0]->message->content); // Add AI's response to history $chat_sessions[$chat_id][] = ["role" => "assistant", "content" => $answer]; // Return AI's response return $answer;}
PHP
<?php// Create the first chat and send messages$chat_id1 = create_chat();echo "Chat 1, First Message: " . send_message($chat_id1, "I'm having trouble with my recent order. Can you help me track it?") . "\n";echo "Chat 1, Follow-up Message: " . send_message($chat_id1, "It was supposed to arrive yesterday but hasn't. What should I do next?") . "\n";?>
text
Chat 1, First Message: Sure, I can help with that. Could you please provide your order number?Chat 1, Follow-up Message: I recommend checking with the delivery service for any updates. If there's no information, please contact our support team for further assistance.
PHP
<?php// Create the second chat and send messages$chat_id2 = create_chat();echo "Chat 2, First Message: " . send_message($chat_id2, "I'm interested in upgrading my membership. What are the benefits?") . "\n";echo "Chat 2, Follow-up Message: " . send_message($chat_id2, "Could you guide me through the upgrade process?") . "\n";?>
text
Chat 2, First Message: Upgrading your membership offers benefits such as exclusive discounts, early access to new features, and priority customer support.Chat 2, Follow-up Message: Certainly! To upgrade, please visit your account settings and select the 'Upgrade Membership' option. Follow the prompts to complete the process.