In the previous lesson, we explored the SessionManager class, which is responsible for managing tutoring session data within our application. Now, we will take the next step by building the Tutor Service Layer. This layer is essential for integrating a language model with tutoring sessions, allowing us to process student queries and generate tailored explanations. By the end of this lesson, you will understand how to set up the TutorService class, create tutoring sessions, and process academic questions using a language model.
The service layer acts as a bridge between the part of the application that manages data and the part that generates educational responses. It is responsible for orchestrating the flow of data and ensuring that student interactions are handled effectively. Let's dive into the details of setting up this important component.
Setting Up the TutorService Class
Loading the System Prompt
Creating a New Tutoring Session
Processing Student Queries
Example: Simulating a Tutoring Session
Summary and Next Steps
In this lesson, we explored the TutorService class and its role in integrating a language model with tutoring sessions. We learned how to set up the class, load the system prompt, create sessions, and process student queries. The service layer is a vital component of our personal tutor application, ensuring that student interactions are handled effectively and that educational content is delivered in a clear and engaging manner.
As you move on to the practice exercises, take the opportunity to experiment with the TutorService 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!
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
The TutorService class is the heart of our service layer. It is responsible for managing tutoring sessions and interacting with the language model to generate educational responses. To begin, we need to set up the class and its components.
First, we need to make sure we have access to the SessionManager from our previous lesson. We also need a way to make requests to the language model's API and a method to load the system prompt from a file. Here's how the class is initialized:
In this setup, we instantiate SessionManager to manage tutoring data, set up a Guzzle HTTP client for API requests, and load the systemPrompt using the loadSystemPrompt method, which we'll discuss next.
The system prompt is a crucial component that guides the tutor's responses. It provides context and instructions, ensuring that the tutor behaves like an effective educational assistant. In this section, we'll implement the loadSystemPrompt method to load the prompt from a file.
PHP
private function loadSystemPrompt(string $filePath): string{ try { $content = file_get_contents($filePath); if ($content === false) { throw new \Exception("File not found or could not be read"); } return $content; } catch (\Exception $e) { echo "Error loading system prompt: " . $e->getMessage() . PHP_EOL; return "You are a helpful tutor."; }}
This method attempts to read the system prompt from a specified file path. If successful, it returns the prompt as a string. If the file is missing or cannot be read, it returns a default prompt. This ensures that the application can continue functioning even if the file is missing or corrupted.
Creating a new tutoring session is a fundamental task of the TutorService. The createSession method is responsible for generating a unique session ID and initializing a tutoring session using the SessionManager.
PHP
public function createSession(string $studentId): string{ $sessionId = uniqid('', true); $this->sessionManager->createSession($studentId, $sessionId, $this->systemPrompt); return $sessionId;}
In this method, we generate a unique sessionId using a unique identifier function. We then call the createSession method of SessionManager, passing the studentId, sessionId, and systemPrompt. This initializes a new tutoring session, which is ready to receive student queries.
The processQuery method is where the educational magic happens. It processes student questions, interacts with the language model to generate tutoring explanations, and updates the session history. Below, we outline the steps involved in this process, followed by the corresponding code implementation:
Retrieve the session using getSession, and raise an error if the session is not found.
Add the student's query to the session history.
Send the conversation, including the system prompt and all previous exchanges, to the language model to generate a response.
Add the tutor's explanation to the session history and return it to the student.
Handle any errors with the API client gracefully.
PHP
public function processQuery(string $studentId, string $sessionId, string $query): string{ $session = $this->sessionManager->getSession($studentId, $sessionId); if (!$session) { throw new \ValueError("Session not found"); } // Add student query $this->sessionManager->addMessage($studentId, $sessionId, "user", $query); try { // Get AI response $conversation = $this->sessionManager->getConversation($studentId, $sessionId); $response = $this->client->post('v1/chat/completions', [ 'json' => [ 'model' => 'deepseek-ai/DeepSeek-V3', 'messages' => $conversation, 'temperature' => 0.7, 'max_tokens' => 500 ] ]); $responseBody = json_decode($response->getBody()->getContents(), true); $aiMessage = $responseBody['choices'][0]['message']['content']; // Add AI response to session history $this->sessionManager->addMessage($studentId, $sessionId, "assistant", $aiMessage); return $aiMessage; } catch (\Exception $e) { throw new \RuntimeException("Error getting AI response: " . $e->getMessage()); }}
In this process, we configure the language model with specific parameters to optimize its educational performance. The temperature is set to 0.7, which balances accuracy and creativity in the tutor's explanations, ensuring they are both informative and engaging. The max_tokens is set to 500, allowing the model to provide detailed educational content without overwhelming the student, thus maintaining an effective learning experience.
Let's see the TutorService in action by simulating a tutoring session. We'll create a script to initialize a tutoring session and process a student's academic query.
PHP
<?phprequire_once __DIR__ . '/src/Service/TutorService.php';use app\Service\TutorService;// Initialize the tutor service$tutorService = new TutorService();// Simulate a student ID$studentId = "student123";// Create a new tutoring session$sessionId = $tutorService->createSession($studentId);echo "Tutoring session created with ID: $sessionId\n";// Simulate sending a tutoring query$studentQuery = "Can you explain the principles of supply and demand in economics?";try { $tutorResponse = $tutorService->processQuery($studentId, $sessionId, $studentQuery); echo "Tutor Response: $tutorResponse\n";} catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n";}
In this example, we initialize the TutorService, simulate a student ID, and create a new tutoring session, printing the session ID. We then simulate sending an academic question and print the tutor's response, demonstrating the flow from student query to tutoring explanation and showcasing the functionality of the TutorService.
Tutoring session created with ID: 01a17870-8a4f-4b6f-a3ce-f04e1136d597Tutor Response: Supply and demand are fundamental principles in economics that describe how prices are determined in a market economy. Let me explain each concept and how they interact:1. Supply: This refers to the quantity of a good or service that producers are willing and able to offer for sale at various price points. - The law of supply states that as the price of a good increases, the quantity supplied also increases (and vice versa). - This creates an upward-sloping supply curve when plotted on a graph with price on the vertical axis and quantity on the horizontal axis.2. Demand: This refers to the quantity of a good or service that consumers are willing and able to purchase at various price points. - The law of demand states that as the price of a good increases, the quantity demanded decreases (and vice versa). - This creates a downward-sloping demand curve on the same type of graph.3. Market Equilibrium: This occurs at the intersection of the supply and demand curves. - At this point, the quantity that producers want to supply exactly equals the quantity that consumers want to buy. - The price at this intersection is called the equilibrium price, and the quantity is called the equilibrium quantity.4. Price Mechanism: When markets are not in equilibrium, the price acts as a signal: - If price is above equilibrium, there's a surplus (excess supply), which puts downward pressure on prices. - If price is below equilibrium, there's a shortage (excess demand), which puts upward pressure on prices.5. Shifts in Supply and Demand: Various factors can cause entire curves to shift: - Supply shifters include technology, input costs, number of sellers, and expectations. - Demand shifters include income, preferences, number of buyers, and expectations.These principles help explain how markets allocate resources efficiently and how changes in market conditions affect prices and quantities.Does this explanation help? Would you like me to elaborate on any specific aspect of supply and demand?
This output illustrates a successful tutoring interaction where a new session is created, and the tutor responds to the student's economics question with a comprehensive explanation. The tutor's response demonstrates the system's ability to provide relevant, structured, and educational content, showcasing how a language model can be effectively used for personalized academic support.
text
Tutoring session created with ID: 01a17870-8a4f-4b6f-a3ce-f04e1136d597Tutor Response: Supply and demand are fundamental principles in economics that describe how prices are determined in a market economy. Let me explain each concept and how they interact:1. Supply: This refers to the quantity of a good or service that producers are willing and able to offer for sale at various price points. - The law of supply states that as the price of a good increases, the quantity supplied also increases (and vice versa). - This creates an upward-sloping supply curve when plotted on a graph with price on the vertical axis and quantity on the horizontal axis.2. Demand: This refers to the quantity of a good or service that consumers are willing and able to purchase at various price points. - The law of demand states that as the price of a good increases, the quantity demanded decreases (and vice versa). - This creates a downward-sloping demand curve on the same type of graph.3. Market Equilibrium: This occurs at the intersection of the supply and demand curves. - At this point, the quantity that producers want to supply exactly equals the quantity that consumers want to buy. - The price at this intersection is called the equilibrium price, and the quantity is called the equilibrium quantity.4. Price Mechanism: When markets are not in equilibrium, the price acts as a signal: - If price is above equilibrium, there's a surplus (excess supply), which puts downward pressure on prices. - If price is below equilibrium, there's a shortage (excess demand), which puts upward pressure on prices.5. Shifts in Supply and Demand: Various factors can cause entire curves to shift: - Supply shifters include technology, input costs, number of sellers, and expectations. - Demand shifters include income, preferences, number of buyers, and expectations.These principles help explain how markets allocate resources efficiently and how changes in market conditions affect prices and quantities.Does this explanation help? Would you like me to elaborate on any specific aspect of supply and demand?