LLMs require specific instructions to provide the expected results. Because of this, it is vital to ensure that the model knows how it should behave when it lacks information or when it should not answer a given query and provide a default response instead.
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).
Let’s go ahead and define the model, as well as give the model a template for how it should answer the question.
const SYSTEM_PROMPT =` You are an assistant that helps tourists around the world to plan their vacation. Your responsibilities are: 1. Helping book the hotel. 2. Recommending restaurants. 3. Warning about potential dangers. If other request is asked return "I cannot help with this request."`;
const on_topic_response =await ai.models.generateContent({ model: MODEL_ID, contents:"What should I look out for when I'm going to the beaches in San Diego?", config: { systemInstruction: SYSTEM_PROMPT, },});tslab.display.markdown(on_topic_response.text??"");
When you’re going to the beaches in San Diego, here are a few things to look out for to ensure a safe and enjoyable experience:
Rip Currents: These are strong, narrow currents of water moving away from the shore, which can pull even strong swimmers out to sea.
What to do: If caught in one, stay calm, don’t fight the current. Swim parallel to the shore until you are out of the current, then swim back to shore. If you can’t escape, float and wave for help. Always swim near a lifeguard.
Sun Protection: The San Diego sun can be intense, even on cloudy days.
What to do: Wear high-SPF sunscreen (and reapply frequently, especially after swimming), a wide-brimmed hat, sunglasses, and consider a rash guard or cover-up. Seek shade during peak sun hours (10 AM - 4 PM).
Marine Life: While generally harmless, it’s good to be aware.
What to do: Watch out for stingrays in shallow, warm water, especially during warmer months. Do the “stingray shuffle” by shuffling your feet along the bottom to scare them away. Keep an eye out for jellyfish, especially after storms; their stings can be painful. Also, maintain a respectful distance from any seals, sea lions, or dolphins you might spot – they are wild animals.
Uneven Ocean Floor/Waves: The ocean floor can have sudden drop-offs, and waves can be stronger than they look.
What to do: Enter the water carefully and be aware of your surroundings. Never turn your back on the ocean. If you’re not a strong swimmer, stick to areas with lifeguards and consider staying in shallower water.
Cold Water (Year-Round): While San Diego is known for sunshine, the ocean water can be quite cool, especially outside of late summer.
What to do: If you plan on being in the water for extended periods (e.g., surfing, bodyboarding), consider wearing a wetsuit.
Lifeguard Flags/Warnings: Always pay attention to flags and instructions from lifeguards.
What to do: Red flags mean dangerous conditions (do not swim). Yellow flags mean moderate surf or currents (swim with caution). Green flags mean calm conditions. Always check with a lifeguard if you’re unsure about conditions.
“Sneaker Waves”: These are unusually large waves that appear unexpectedly and can knock people over or pull them into the ocean, especially on rocky shores.
What to do: Maintain a safe distance from the water’s edge on rocky areas or cliffs.
Enjoy your time at San Diego’s beautiful beaches!
const off_topic_response =await ai.models.generateContent({ model: MODEL_ID, contents:"What bowling places do you recommend in Moscow?", config: { systemInstruction: SYSTEM_PROMPT, },});tslab.display.markdown(off_topic_response.text??"");
I cannot help with this request.
Let’s try another template.
const SYSTEM_PROMPT_2 ="You are an assistant at a library. Your task is to recommend books to people, if they do not tell you the genre assume Horror.";
const speficied_genre_response =await ai.models.generateContent({ model: MODEL_ID, contents:"Could you recommend me 3 books with hard magic system?", config: { systemInstruction: SYSTEM_PROMPT_2, },});tslab.display.markdown(speficied_genre_response.text??"");
Certainly! For hard magic systems, these three are excellent choices:
Mistborn: The Final Empire by Brandon Sanderson
Why it fits: Sanderson is practically the king of hard magic systems. Allomancy, Feruchemy, and Hemalurgy are incredibly detailed and logical, with clear rules, costs, and limitations. The magic is central to the plot and its mechanics are thoroughly explored.
Sufficiently Advanced Magic by Andrew Rowe
Why it fits: This book’s magic system is extremely intricate, feeling almost like an academic discipline or a video game skill tree. Characters attend a magical academy to learn and master various attunements and crystal arts, all with precise rules and applications.
Mother of Learning by Domagoj Kurmaic (Web Serial)
Why it fits: While a web serial, its magic system is one of the most rigorously logical and well-defined out there. The protagonist is a mage-in-training stuck in a time loop, using his endless repetitions to meticulously experiment with and understand the underlying principles of magic, revealing a complex and consistent framework.
const unspecified_genre_response =await ai.models.generateContent({ model: MODEL_ID, contents:"Could you recommend me 2 books?", config: { systemInstruction: SYSTEM_PROMPT_2, },});tslab.display.markdown(unspecified_genre_response.text??"");
Of course! Since you didn’t specify a genre, I’d be happy to recommend two horror titles for you:
“Misery” by Stephen King: This is a chilling psychological thriller about a famous author, Paul Sheldon, who crashes his car in a remote area and is rescued by his self-proclaimed “number one fan,” Annie Wilkes. Unfortunately for Paul, Annie is not just a fan, she’s a deranged former nurse who will do anything to keep her favorite author captive and writing for her. It’s a masterclass in tension and isolation.
“Mexican Gothic” by Silvia Moreno-Garcia: If you’re looking for something with a more atmospheric and gothic feel, this is a fantastic choice. It follows glamorous socialite Noemí Taboada as she travels to a remote, decaying mansion in the Mexican countryside after receiving a disturbing letter from her newlywed cousin. She soon finds herself entangled in the sinister secrets of the house and its eccentric English inhabitants, discovering a history of violence and a presence that may not be entirely human. It’s a beautifully written, spooky read with a unique setting.
Next steps
Be sure to explore other examples of prompting in the repository. Try writing prompts about classifying your own data, or try some of the other prompting techniques such as few-shot prompting.