Managing Multiple Chat Sessions with OpenAI in JavaScript

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.

Creating Unique Chat Sessions

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 the uuidv4 function from the uuid library to generate a unique identifier for each chat session. When a new chat session is created, a unique chatId is generated, and an empty conversation history is initialized.

import { v4 as uuidv4 } from 'uuid';

// Store all active chat sessions
const chatSessions = {};

// Define a common system prompt for all conversations
const systemPrompt = {
    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 identifier
function createChat() {
    const chatId = uuidv4();  // Create unique session identifier
    chatSessions[chatId] = [];  // Initialize empty conversation history
    chatSessions[chatId].push(systemPrompt);  // Add system prompt to conversation history
    return chatId;
}

In our example, we store conversation history in an object called chatSessions, where each key is a unique chatId. 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

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 sendMessage function to handle this process. The function takes a chatId and a userMessage 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.

import OpenAI from 'openai';

// Initialize the OpenAI client
const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,
});

async function sendMessage(chatId, userMessage) {
    // Verify chat session exists
    if (!chatSessions[chatId]) {
        throw new Error("Chat session not found!");
    }
    // Add user's message to history
    chatSessions[chatId].push({ role: "user", content: userMessage });
    // Get AI response using conversation history
    const response = await openai.chat.completions.create({
        model: "gpt-4",
        messages: chatSessions[chatId]
    });
    // Extract and clean AI's response
    const answer = response.choices[0].message.content.trim();
    // Add AI's response to history
    chatSessions[chatId].push({ role: "assistant", content: answer });
    // Return AI's response
    return answer;
}
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