Welcome back! In the previous lesson, you learned how to send a simple message to DeepSeek's language model and receive a response. Now, we will take a step further by exploring model parameters that allow you to customize the AI tutor's responses. These parameters are crucial for tailoring the tutor's behavior to meet specific educational needs. In this lesson, we will focus on four key parameters: max_tokens, temperature, presence_penalty, and frequency_penalty. Understanding these parameters will enable you to control the creativity, length, and content of the AI's explanations, enhancing your personal tutor's effectiveness.
Controlling Response Length with Max Tokens
Exploring Temperature
Encouraging New Topics with Presence Penalty
Reducing Repetition with Frequency Penalty
Example: Implementing Model Parameters in Code
Summary and Preparation for Practice
In this lesson, we explored how to use model parameters to customize AI tutor responses. You learned about the temperature, max_tokens, presence_penalty, and frequency_penalty parameters and saw how they can be applied in code. These tools allow you to control the creativity, length, and content of the AI's explanations, enhancing your personal tutor's educational effectiveness.
As you move on to the practice exercises, I encourage you to experiment with different parameter settings to see their effects firsthand. This hands-on practice will reinforce what you've learned and prepare you for the next unit, where we'll delve deeper into managing tutoring sessions and message types. Keep up the great work, and enjoy the journey of creating your personal tutor with DeepSeek!
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
The max_tokens parameter sets a hard limit on the number of tokens the AI can generate in its response. A "token" can be a whole word or just part of a word. For example, "tutor" might be one token, while "explanation" could be split into multiple tokens. It's important to note that token counts vary across different models, words, and languages — so the same text might have a different token count depending on these factors.
When you set max_tokens, you specify the maximum number of tokens the AI can produce. This is a strict limit, meaning the model will stop generating text once it reaches this count, even if it results in an incomplete answer.
Here's an example where we set max_tokens to 150:
PHP
<?phprequire 'vendor/autoload.php';use GuzzleHttp\Client;// Initialize the HTTP client$client = new Client([ 'base_uri' => getenv('OPENAI_BASE_URL'), 'headers' => [ 'Authorization' => 'Bearer ' . getenv('OPENAI_API_KEY'), 'Content-Type' => 'application/json', ]]);// Define a query$prompt = "Tell me a fun fact about space.";// Send a request with max_tokens parameter$response = $client->post('v1/chat/completions', [ 'json' => [ 'model' => 'deepseek-ai/DeepSeek-V3', 'messages' => [['role' => 'user', 'content' => $prompt]], 'max_tokens' => 150, ],]);// Process the response$body = json_decode($response->getBody(), true);$reply = trim($body['choices'][0]['message']['content']);echo "Answer: " . $reply;?>
text
Here's a fun space fact: **Neutron stars are so dense that a single teaspoon of their material would weigh about 6 billion tons on Earth!** These incredibly dense remnants of supernova explosions pack more mass than our Sun into a sphere only about 12 miles (20 km) wide. Their gravity is so strong that if you dropped an object from just one meter above the surface, it would hit the star at around **7 million km/h (4.3 million mph)!** Want another wild fact? Some neutron stars, called **pulsars**, spin hundreds of times per second, emitting beams of radiation like cosmic lighthouses! 🌟
By setting max_tokens to 150, you impose a hard limit on the number of tokens the AI tutor can generate in its explanation. This may result in responses being abruptly cut off if the model hasn't completed its intended thought. Importantly, the max_tokens parameter doesn't make the model inherently more concise or brief — it simply restricts explanation length. The model isn't consciously summarizing or adjusting content to fit within this limit; rather, it continues generating text until reaching the token limit. Primarily, this parameter is valuable for managing usage rates and controlling the cost of API requests when building your personal tutor.
The temperature parameter is a fascinating aspect of AI interaction. It controls the randomness or creativity of the AI's responses. A lower temperature value, such as 0.2, makes the AI's output more deterministic and focused, often resulting in more predictable explanations. Conversely, a higher temperature value, like 0.8, encourages the AI to generate more diverse and creative responses, which can be useful for providing varied educational content and explanations.
For example, consider the following code snippet where we set the temperature to 0.6:
PHP
<?phprequire 'vendor/autoload.php';use GuzzleHttp\Client;// Initialize the HTTP client$client = new Client([ 'base_uri' => getenv('OPENAI_BASE_URL'), 'headers' => [ 'Authorization' => 'Bearer ' . getenv('OPENAI_API_KEY'), 'Content-Type' => 'application/json', ]]);// Define a query$prompt = "Tell me a fun fact about space.";// Send a request with temperature parameter$response = $client->post('v1/chat/completions', [ 'json' => [ 'model' => 'deepseek-ai/DeepSeek-V3', 'messages' => [['role' => 'user', 'content' => $prompt]], 'temperature' => 0.6, ],]);// Process the response$body = json_decode($response->getBody(), true);$reply = trim($body['choices'][0]['message']['content']);echo "Answer: " . $reply;?>
text
Here's a fun space fact: **There’s a giant water vapor cloud in space**—**containing 140 trillion times the water in Earth’s oceans**—floating around a supermassive black hole **12 billion light-years away**! This "reservoir" was discovered in 2011 near a quasar (APM 08279+5255) and is the largest known water supply in the universe. Even cooler? The vapor is spread across hundreds of light-years and exists in a state that’s impossible on Earth—**a superheated, swirling mass of gas and ice particles**. Bonus: **The water was already there when the universe was just 1.6 billion years old**—showing how quickly cosmic chemistry can work! Want another wild space fact? Just ask! 🚀
With a temperature of 0.6, the AI tutor is likely to provide an explanation that balances creativity and factual accuracy. Experimenting with different temperature values will help you find the right balance for your specific tutoring scenarios. A lower temperature might be preferable for mathematical or scientific explanations where precision is crucial, while a higher temperature could work better for creative writing or brainstorming sessions.
The presence_penalty parameter is a powerful tool for encouraging the AI tutor to introduce new concepts in its explanations. It works by penalizing the AI for using words that have already appeared in the conversation, thus promoting diversity in the dialogue. A low presence_penalty value, such as -1.0, means the AI is less discouraged from repeating words, leading to more focused explanations. In contrast, a high presence_penalty value, like 1.0, strongly encourages the AI to explore new topics, resulting in more varied and diverse tutoring content.
Consider the following code where we set the presence_penalty to 0.5:
PHP
<?phprequire 'vendor/autoload.php';use GuzzleHttp\Client;// Initialize the HTTP client$client = new Client([ 'base_uri' => getenv('OPENAI_BASE_URL'), 'headers' => [ 'Authorization' => 'Bearer ' . getenv('OPENAI_API_KEY'), 'Content-Type' => 'application/json', ]]);// Define a query$prompt = "Tell me a fun fact about space.";// Send a request with presence_penalty parameter$response = $client->post('v1/chat/completions', [ 'json' => [ 'model' => 'deepseek-ai/DeepSeek-V3', 'messages' => [['role' => 'user', 'content' => $prompt]], 'presence_penalty' => 0.5, ],]);// Process the response$body = json_decode($response->getBody(), true);$reply = trim($body['choices'][0]['message']['content']);echo "Answer: " . $reply;?>
text
Sure! Here's a fun space fact: **The Moon is slowly drifting away from Earth at about 3.8 centimeters (1.5 inches) per year!** 🌕 This happens because of tidal forces between Earth and the Moon, which transfer energy and gradually push the Moon into a higher orbit. Don’t worry, though—it’ll take *billions* of years before this has a major impact. Want another cool space fact? Just ask! 🚀
With a presence_penalty of 0.5, the AI tutor is more likely to introduce new concepts and provide varied explanations. This can be particularly useful in educational scenarios where you want to expose students to a broader range of related ideas or approaches to a problem.
The frequency_penalty parameter helps reduce repetition in the AI's explanations by discouraging the repeated use of the same words or phrases. This encourages more varied and engaging educational content. A low frequency_penalty value, such as 0.0, allows for more repetition, which can be useful for reinforcing key concepts. Conversely, a high frequency_penalty value, such as 1.0, reduces repetition, promoting more dynamic and varied explanations.
While presence_penalty and frequency_penalty serve different functions in controlling repetition:
Presence penalty: Encourages the AI to bring up new concepts by penalizing the model for using words that have already appeared in the conversation history.
Frequency penalty: Reduces repetition by penalizing the model for using the same words or phrases multiple times within a single explanation.
This distinction allows you to manage both the range of topics and the variety of language in the AI tutor's output.
In the following example, we set the frequency_penalty to 0.2:
PHP
<?phprequire 'vendor/autoload.php';use GuzzleHttp\Client;// Initialize the HTTP client$client = new Client([ 'base_uri' => getenv('OPENAI_BASE_URL'), 'headers' => [ 'Authorization' => 'Bearer ' . getenv('OPENAI_API_KEY'), 'Content-Type' => 'application/json', ]]);// Define a query$prompt = "Tell me a fun fact about space.";// Send a request with frequency_penalty parameter$response = $client->post('v1/chat/completions', [ 'json' => [ 'model' => 'deepseek-ai/DeepSeek-V3', 'messages' => [['role' => 'user', 'content' => $prompt]], 'frequency_penalty' => 0.2, ],]);// Process the response$body = json_decode($response->getBody(), true);$reply = trim($body['choices'][0]['message']['content']);echo "Answer: " . $reply;?>
text
Sure! Here's a fun space fact: **Neutron stars are so dense that a sugar-cube-sized amount of their material would weigh about a billion tons on Earth—roughly as much as Mount Everest!** These incredibly dense remnants of supernova explosions spin extremely fast, with some rotating hundreds of times per second. Some even emit beams of radiation, making them detectable as *pulsars*. Want another wild fact? Let me know! 🚀
By applying a frequency_penalty of 0.2, you can reduce redundancy in the tutor's explanations while still allowing for some repetition when necessary for educational purposes. This results in more dynamic and engaging educational content, striking a balance between variation and reinforcement of important concepts.
Let's bring it all together with a complete code example that incorporates all the parameters we've discussed:
PHP
<?phprequire 'vendor/autoload.php';use GuzzleHttp\Client;// Initialize the HTTP client$client = new Client([ 'base_uri' => getenv('OPENAI_BASE_URL'), 'headers' => [ 'Authorization' => 'Bearer ' . getenv('OPENAI_API_KEY'), 'Content-Type' => 'application/json', ]]);// Define a query$prompt = "Tell me a fun fact about space.";// Send a request with all parameters$response = $client->post('v1/chat/completions', [ 'json' => [ 'model' => 'deepseek-ai/DeepSeek-V3', 'messages' => [['role' => 'user', 'content' => $prompt]], 'max_tokens' => 150, // Limits explanation length 'temperature' => 0.6, // Controls explanation creativity 'presence_penalty' => 0.5, // Encourages introduction of new concepts 'frequency_penalty' => 0.2, // Reduces repetitive details ],]);// Process the response$body = json_decode($response->getBody(), true);$reply = trim($body['choices'][0]['message']['content']);echo "Answer: " . $reply;?>
text
Here’s a fun space fact: **Neutron stars are so dense that a single teaspoon of their material would weigh about 6 billion tons on Earth!** These incredibly dense stellar remnants form when massive stars collapse in supernova explosions. Despite being only about 12–15 miles (20–25 km) wide, they pack more mass than our Sun. Their gravity is so strong that if you dropped an object from just one meter above the surface, it would hit the star at millions of miles per hour! Want another wild fact? Some neutron stars spin hundreds of times per second—imagine a cosmic lighthouse blasting beams of radiation across the galaxy! 🌟
In this example, we use all four parameters to customize the AI's response. By adjusting these parameters, you can fine-tune the tutor's behavior to meet your specific requirements. When adjusting parameters like temperature or penalties, keep a log of your outputs and parameter values to understand how each setting affects the AI’s behavior. Small incremental changes (e.g., increasing temperature by 0.1) are usually better than large jumps, especially when fine-tuning your tutor’s tone and explanation style.
When you run this code, you should see a response that reflects the balance of creativity, length, and content diversity that you've set.