Building a Session Manager for Tutoring Conversations in Go

Building the Session Manager in Go

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 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 Go structs and methods.

Initializing the SessionManager

In Go, we use structs to define complex data types. The SessionManager struct will handle the storage and management of tutoring session data. We'll also define supporting types for session data and messages.

Let's start by defining the necessary types and a constructor-like function to initialize the SessionManager:

type Message struct {
    Role    string
    Content string
}

type Session struct {
    SystemPrompt string
    Messages     []Message
}

// SessionManager manages all sessions for all students.
type SessionManager struct {
    sessions map[string]map[string]*Session // studentID -> sessionID -> Session
}

// NewSessionManager creates and returns a new SessionManager.
func NewSessionManager() *SessionManager {
    return &SessionManager{
        sessions: make(map[string]map[string]*Session),
    }
}

Here, SessionManager uses a nested map to store sessions for each student. The first key is the studentID, and the second key is the sessionID. This structure allows us to efficiently manage multiple tutoring sessions for different students.

Creating a New Session

To create a new session, we'll add a method to SessionManager called CreateSession. This method takes a studentID, sessionID, and systemPrompt as parameters and initializes a new session.

func (sm *SessionManager) CreateSession(studentID, sessionID, systemPrompt string) {
    if _, ok := sm.sessions[studentID]; !ok {
        sm.sessions[studentID] = make(map[string]*Session)
    }
    sm.sessions[studentID][sessionID] = &Session{
        SystemPrompt: systemPrompt,
        Messages:     []Message{},
    }
}

This method checks if the studentID exists in the sessions map. If not, it creates a new entry. Then, it initializes the session with the provided systemPrompt and an empty slice for messages.

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