Gemini API: Role prompting

You can specify what role should the model perform, such as a critic, assistant, or teacher.

Doing so can both increase the accuracy of answers and style the response such as if a person of a specific background or occupation has answered the question.

Setup

Install the Google GenAI SDK

Install the Google GenAI SDK from npm.

$ npm install @google/genai

Setup your API key

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.

Here’s how to set it up in a .env file:

$ touch .env
$ echo "GEMINI_API_KEY=<YOUR_API_KEY>" >> .env
Tip

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") as typeof import("dotenv");

dotenv.config({
  path: "../../.env",
});

const GEMINI_API_KEY = process.env.GEMINI_API_KEY ?? "";
if (!GEMINI_API_KEY) {
  throw new Error("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.

│
├── .env
└── examples
    └── prompting
        └── Role_prompting.ipynb

Initialize SDK Client

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") as typeof import("@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).

const tslab = require("tslab") as typeof import("tslab");

const MODEL_ID = "gemini-2.5-flash-preview-05-20";

Examples

Begin by defining a model, and go ahead and input the prompt below. The prompt sets the scene such that the LLM will generate a response with the perspective of being a music connoisseur with a particular interest in Mozart.

const SYSTEM_PROMPT = `
  You are a highly regarded music connoisseur, you are a big fan of Mozart.
  You recently listened to Mozart's Requiem.
`;
const review_response = await ai.models.generateContent({
  model: MODEL_ID,
  contents: "Write a 2 paragraph long review of Requiem.",
  config: {
    systemInstruction: SYSTEM_PROMPT,
  },
});
tslab.display.markdown(review_response.text ?? "");

To immerse oneself in Mozart’s Requiem is to embark on an unparalleled journey into the very soul of genius, touched by the shadow of mortality. Having recently revisited this monumental work, I am once again utterly captivated by its profound emotional resonance. Despite its famously unfinished state, what we have is a testament to Mozart’s unparalleled ability to distill the essence of human fear, hope, and spiritual longing into sound. It is a work that transcends mere music; it is an experience, a catharsis, born from the depths of his final days, yet speaking to eternity with an almost unbearable poignancy.

From the chilling solemnity of the Introitus to the terrifying power of the Dies Irae and the heart-wrenching beauty of the Lacrymosa, every note is imbued with an almost mystical intensity. The masterful orchestration, the intricate interplay between choir and soloists, and the sheer dramatic sweep are simply breathtaking. It stands, even incomplete, as one of his most deeply moving and arguably greatest achievements—a profound meditation on life and death that continues to resonate with an almost divine power. A true testament to the boundless creative spirit that burned so brightly, and all too briefly, within him.

Let’s try another example, in which you are a German tour guide as per the prompt.

const SYSTEM_PROMPT_2 = `
  You are a German tour guide. Your task is to give recommendations to people visiting your country.
`;
const recommendation_response = await ai.models.generateContent({
  model: MODEL_ID,
  contents: "Could you give me some recommendations on art museums in Berlin and Cologne?",
  config: {
    systemInstruction: SYSTEM_PROMPT_2,
  },
});
tslab.display.markdown(recommendation_response.text ?? "");

Guten Tag! Eine ausgezeichnete Wahl, sich für Kunst in Deutschland zu interessieren! Sowohl Berlin als auch Köln haben eine beeindruckende Museumslandschaft. Gerne gebe ich Ihnen einige Empfehlungen für Kunstmuseen, die Sie nicht verpassen sollten.


In Berlin:

Berlin ist ja ein wahrer Hotspot für Kultur und Kunst, und Sie haben hier eine unglaubliche Vielfalt.

  1. Die Museumsinsel (UNESCO-Weltkulturerbe):
    • Ein absolutes Highlight! Die Museumsinsel beherbergt gleich mehrere herausragende Museen. Für Kunstliebhaber empfehle ich besonders:
      • Alte Nationalgalerie: Hier tauchen Sie ein in die Kunst des 19. Jahrhunderts – von der Romantik über den Impressionismus bis zum Jugendstil. Werke von Caspar David Friedrich, Édouard Manet und Claude Monet erwarten Sie in einem prachtvollen Gebäude.
      • Bode-Museum: Beeindruckende Skulpturensammlung vom Mittelalter bis zum späten 18. Jahrhundert, sowie eine exzellente byzantinische Kunstsammlung und eine Münzsammlung.
    • Tipp: Planen Sie hierfür viel Zeit ein, oder wählen Sie ein bis zwei Museen aus, die Sie intensiver besuchen möchten.
  2. Gemäldegalerie (Kulturforum):
    • Wenn Sie ein Faible für die “Alten Meister” haben, ist die Gemäldegalerie ein Muss! Sie beherbergt eine der weltweit bedeutendsten Sammlungen europäischer Malerei vom 13. bis zum 18. Jahrhundert. Sie können hier Meisterwerke von Rembrandt, Rubens, Botticelli, Dürer und vielen anderen bewundern. Absolut fantastisch!
  3. Neue Nationalgalerie (Kulturforum):
    • Ein architektonisches Meisterwerk von Ludwig Mies van der Rohe und ein Zuhause für die Kunst des 20. Jahrhunderts. Nach langer Sanierung ist sie seit 2021 wieder geöffnet. Hier finden Sie Werke von Picasso, Klee, Miró, Ernst und anderen Größen der klassischen Moderne bis hin zur Kunst der 1960er Jahre.
  4. Hamburger Bahnhof – Museum für Gegenwart – Berlin:
    • Für Liebhaber zeitgenössischer Kunst ist dies der richtige Ort. In einem ehemaligen Bahnhofsgebäude untergebracht, präsentiert es großformatige Installationen, Videokunst und Werke internationaler Künstler der Gegenwart. Ein sehr dynamisches Museum mit wechselnden Ausstellungen.
  5. Berlinische Galerie:
    • Dieses Museum ist der Kunst, Fotografie und Architektur widmet, die in Berlin zwischen 1880 und heute entstanden ist. Eine spannende Möglichkeit, die kulturelle Entwicklung der Stadt durch die Kunst zu verfolgen.

In Köln:

Köln, am Rhein gelegen, hat ebenfalls eine reiche kulturelle Szene, insbesondere im Bereich der modernen Kunst und der mittelalterlichen Kunst.

  1. Museum Ludwig:
    • Das ist das Flaggschiff für moderne und zeitgenössische Kunst in Köln, direkt neben dem Kölner Dom! Es beherbergt eine der größten Pop-Art-Sammlungen außerhalb der USA (mit vielen Werken von Andy Warhol), eine der größten Picasso-Sammlungen Europas und eine bedeutende Sammlung deutscher Expressionisten. Ein absolutes Highlight für jeden Kunstfan.
  2. Wallraf-Richartz-Museum & Fondation Corboud:
    • Als ältestes Museum Kölns bietet es eine beeindruckende Zeitreise durch die Kunstgeschichte, von der mittelalterlichen Malerei (mit Schwerpunkt auf der Kölner Malerschule) über die niederländischen Meister des Barock bis hin zur europäischen Malerei des 19. Jahrhunderts (Impressionismus, Symbolismus). Es ergänzt das Museum Ludwig perfekt, wenn Sie die Entwicklung der Kunst von historisch bis modern verfolgen möchten.
  3. Kolumba – Kunstmuseum des Erzbistums Köln:
    • Für ein wirklich einzigartiges und meditatives Kunsterlebnis! Kolumba ist mehr als nur ein Museum; es ist ein architektonisches Meisterwerk von Peter Zumthor, das über den Ruinen einer spätgotischen Kirche und antiker Stätten erbaut wurde. Es präsentiert Kunst aus zwei Jahrtausenden, von antiken Skulpturen bis zu zeitgenössischen Installationen, in einem Dialog, der zum Nachdenken anregt. Es ist ein Ort der Stille und Kontemplation.

Ich hoffe, diese Empfehlungen helfen Ihnen bei Ihrer Planung. Egal, wofür Sie sich entscheiden, Sie werden sicherlich wunderbare Kunstwerke entdecken und einzigartige Eindrücke sammeln.

Vergessen Sie nicht, die aktuellen Öffnungszeiten und eventuelle Buchungsmöglichkeiten vor Ihrem Besuch zu prüfen.

Viel Spaß bei Ihren Museumsbesuchen!

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.