This notebook demonstrates how to use prompting to perform reasoning tasks using the Gemini API’s JS SDK. In this example, you will work through a mathematical word problem using prompting.
The Gemini API can handle many tasks that involve indirect reasoning, such as solving mathematical or logical proofs.
In this example, you will see how the LLM explains given problems step by step.
You can create your API key using Google AI Studio with a single click.
Remember to treat your API key like a password. Don’t accidentally save it in a notebook or source file you later commit to GitHub. In this notebook we will be storing the API key in a .env file. You can also set it as an environment variable or use a secret manager.
Another option is to set the API key as an environment variable. You can do this in your terminal with the following command:
$ export GEMINI_API_KEY="<YOUR_API_KEY>"
Load the API key
To load the API key from the .env file, we will use the dotenv package. This package loads environment variables from a .env file into process.env.
$ npm install dotenv
Then, we can load the API key in our code:
const dotenv =require("dotenv") astypeofimport("dotenv");dotenv.config({ path:"../../.env",});const GEMINI_API_KEY =process.env.GEMINI_API_KEY??"";if (!GEMINI_API_KEY) {thrownewError("GEMINI_API_KEY is not set in the environment variables");}console.log("GEMINI_API_KEY is set in the environment variables");
GEMINI_API_KEY is set in the environment variables
Note
In our particular case the .env is is two directories up from the notebook, hence we need to use ../../ to go up two directories. If the .env file is in the same directory as the notebook, you can omit it altogether.
With the new SDK, now you only need to initialize a client with you API key (or OAuth if using Vertex AI). The model is now set in each call.
const google =require("@google/genai") astypeofimport("@google/genai");const ai =new google.GoogleGenAI({ apiKey: GEMINI_API_KEY });
Select a model
Now select the model you want to use in this guide, either by selecting one in the list or writing it down. Keep in mind that some models, like the 2.5 ones are thinking models and thus take slightly more time to respond (cf. thinking notebook for more details and in particular learn how to switch the thiking off).
Begin by defining some system instructions that will be include when you define and choose the model.
const SYSTEM_PROMPT =` You are a teacher solving mathematical and logical problems. Your task: 1. Summarize given conditions. 2. Identify the problem. 3. Provide a clear, step-by-step solution. 4. Provide an explanation for each step. Ensure simplicity, clarity, and correctness in all steps of your explanation. Each of your task should be done in order and seperately.`;
Next, you can define a logical problem such as the one below.
const logical_response =await ai.models.generateContent({ model: MODEL_ID, contents:` Assume a world where 1 in 5 dice are weighted and have 100% to roll a 6. A person rolled a dice and rolled a 6. Is it more likely that the die was weighted or not? `, config: { systemInstruction: SYSTEM_PROMPT, },});tslab.display.markdown(logical_response.text??"");
Here’s a breakdown of the problem and its solution:
1. Summary of Given Conditions
Prevalence of Weighted Dice: 1 out of every 5 dice is weighted. This means P(Weighted) = 1/5.
Prevalence of Normal Dice: Consequently, 4 out of every 5 dice are not weighted (normal). This means P(Normal) = 4/5.
Weighted Die Outcome: A weighted die has a 100% chance to roll a 6. This means P(Roll 6 | Weighted) = 1.
Normal Die Outcome: A normal die has a 1/6 chance to roll a 6 (assuming a standard fair die). This means P(Roll 6 | Normal) = 1/6.
Observed Event: A person rolled a die and got a 6.
2. Identification of the Problem
The problem asks us to determine, given that a 6 was rolled, whether it is more likely that the die was weighted or not weighted. This is a conditional probability problem, requiring us to calculate the probability of the die being weighted given a 6 was rolled, and compare it to the probability of the die being normal given a 6 was rolled. We need to compare P(Weighted | Roll 6) with P(Normal | Roll 6).
3. Step-by-Step Solution
Step 1: Define Probabilities of Die Type
Probability of a die being weighted, P(W): P(W) = 1/5 = 0.20
Probability of a die being normal (not weighted), P(NW): P(NW) = 1 - P(W) = 4/5 = 0.80
Step 2: Define Probabilities of Rolling a 6 based on Die Type
Probability of rolling a 6 if the die is weighted, P(R6 | W): P(R6 | W) = 1 (100% chance)
Probability of rolling a 6 if the die is normal, P(R6 | NW): P(R6 | NW) = 1/6
Step 3: Calculate the Total Probability of Rolling a 6
To use Bayes’ Theorem, we first need the overall probability of rolling a 6, P(R6). This can happen in two ways: rolling a 6 with a weighted die OR rolling a 6 with a normal die.
Alternatively, since these are the only two possibilities (weighted or normal), P(NW | R6) = 1 - P(W | R6) = 1 - 0.60 = 0.40.
Step 6: Compare the Probabilities
P(Weighted | Roll 6) = 0.60
P(Normal | Roll 6) = 0.40
Since 0.60 > 0.40, it is more likely that the die was weighted.
4. Explanation for Each Step
Step 1: We established the prior probabilities of picking a weighted or normal die from the collection. These are the probabilities before any roll happens.
Step 2: We defined the likelihood of rolling a 6 for each type of die. A weighted die always rolls a 6, while a normal die rolls a 6 only 1 out of 6 times.
Step 3: This step calculates the overall probability of observing a 6, irrespective of the die type. It accounts for both scenarios: rolling a 6 with a weighted die and rolling a 6 with a normal die. This is the denominator in Bayes’ Theorem.
Step 4 & 5: These steps apply Bayes’ Theorem. Bayes’ Theorem allows us to update our initial beliefs (prior probabilities) based on new evidence (rolling a 6). We calculate the posterior probability for each case (weighted or normal die) given the observed outcome (rolling a 6).
P(W | R6) tells us “what is the probability the die was weighted, given we rolled a 6?”
P(NW | R6) tells us “what is the probability the die was normal, given we rolled a 6?”
Step 6: By comparing the calculated posterior probabilities, we can directly answer the question of which scenario (weighted or not weighted) is more likely given the observed roll of a 6. The higher probability indicates the more likely event.
Conclusion: It is more likely that the die was weighted (60% chance) than not weighted (40% chance) after rolling a 6.
const math_response =await ai.models.generateContent({ model: MODEL_ID, contents:"Given a triangle with base b=6 and height h=8, calculate its area", config: { systemInstruction: SYSTEM_PROMPT, },});tslab.display.markdown(math_response.text??"");
Here’s a breakdown of the problem and its solution:
1. Summarize given conditions:
The base of the triangle (b) = 6 units
The height of the triangle (h) = 8 units
2. Identify the problem:
The problem asks us to calculate the area of the triangle.
3. Provide a clear, step-by-step solution:
Step 1: Recall the formula for the area of a triangle. The area (A) of a triangle is given by the formula: A = (1/2) × base × height A = (1/2) × b × h
Step 2: Substitute the given values into the formula. Given b = 6 and h = 8, substitute these values into the formula: A = (1/2) × 6 × 8
Step 3: Perform the multiplication to find the area. First, multiply the base and height: 6 × 8 = 48 Then, multiply by 1/2: A = (1/2) × 48 A = 48 / 2 A = 24
Step 4: State the final answer with appropriate units. The area of the triangle is 24 square units.
4. Provide an explanation for each step:
Step 1: Recall the formula for the area of a triangle.
This step is crucial because the formula A = (1/2) × b × h is the fundamental mathematical relationship that defines how to calculate the area of any triangle, given its base and corresponding height.
Step 2: Substitute the given values into the formula.
By replacing the variables ‘b’ and ‘h’ with their specific numerical values (6 and 8), we transform the general formula into a specific calculation for the given triangle, making it ready to be solved.
Step 3: Perform the multiplication to find the area.
This step is the arithmetic calculation. Multiplying the base by the height gives the area of a rectangle with those dimensions. Dividing by 2 (or multiplying by 1/2) converts this to the area of the triangle, as a triangle can be seen as half of a parallelogram (or rectangle) with the same base and height.
Step 4: State the final answer with appropriate units.
It’s important to include units. Since the base and height were given as “units” (e.g., cm, m, inches), the area is expressed in “square units” (e.g., cm², m², inches²). This clarifies what the number 24 represents in a real-world context.
Next steps
Be sure to explore other examples of prompting in the repository. Try creating your own prompts that include instructions on how to solve basic reasoning problems, or use the prompt given in this notebook as a template.