Building the Session Manager in C#

Building the Session Manager

Welcome back! In the previous lesson, we explored the importance of a robust system prompt and how it guides the behavior of our personal tutor. Now, we will delve into the next step of our journey: building the Session 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 SessionManager class will be the core component of our model layer, responsible for managing tutoring session data effectively. By the end of this lesson, you will understand how to create, manage, and retrieve session data using the SessionManager class.

Creating a New Session

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

public void CreateSession(string userId, string sessionId, string systemPrompt)
{
    if (!sessions.ContainsKey(userId))
    {
        sessions[userId] = new Dictionary<string, SessionData>();
    }

    sessions[userId][sessionId] = new SessionData
    {
        SystemPrompt = systemPrompt,
        Messages = new List<Message>()
    };
}

The CreateSession method checks if the userId exists in sessions. If not, it creates a new entry. Then, it initializes the session with the provided systemPrompt and an empty list for messages.

Retrieving a Session

To access a specific tutoring session, we need the GetSession method. This method retrieves a session based on the userId and sessionId.

public SessionData? GetSession(string userId, string sessionId)
{
    if (sessions.ContainsKey(userId) && sessions[userId].ContainsKey(sessionId))
    {
        return sessions[userId][sessionId];
    }
    return null;
}

The GetSession method safely accesses the nested dictionary, returning the session data if it exists.

Adding Messages to a Session

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

public void AddMessage(string userId, string sessionId, string role, string content)
{
    var session = GetSession(userId, sessionId);
    if (session != null)
    {
        session.Messages.Add(new Message { Role = role, Content = content });
    }
}

The AddMessage method first retrieves the session using GetSession. If the session exists, it appends the message to the session's message list.

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