Skip to content

Commit

Permalink
Use system instructions
Browse files Browse the repository at this point in the history
  • Loading branch information
shilpakancharla committed May 31, 2024
1 parent 4cea2cc commit eae06f7
Showing 1 changed file with 164 additions and 104 deletions.
268 changes: 164 additions & 104 deletions examples/prompting/Role_prompting.ipynb
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "2tRfbqHj6jRN"
},
"source": [
"##### Copyright 2024 Google LLC."
]
],
"metadata": {
"id": "2tRfbqHj6jRN"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"id": "g0TJSlLx6kvB"
},
"outputs": [],
"source": [
"# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
Expand All @@ -29,55 +37,60 @@
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
],
"metadata": {
"id": "g0TJSlLx6kvB"
},
"execution_count": 1,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "sP8PQnz1QrcF"
},
"source": [
"# Gemini API: Role prompting"
]
],
"metadata": {
"id": "sP8PQnz1QrcF"
}
},
{
"cell_type": "markdown",
"metadata": {
"id": "bxGr_x3MRA0z"
},
"source": [
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/prompting/Role_prompting.ipynb\"><img src = \"https://www.tensorflow.org/images/colab_logo_32px.png\"/>Run in Google Colab</a>\n",
" </td>\n",
"</table>"
]
],
"metadata": {
"id": "bxGr_x3MRA0z"
}
},
{
"cell_type": "markdown",
"metadata": {
"id": "ysy--KfNRrCq"
},
"source": [
"You can specify what role should the model perform, such as a critic, assistant, or teacher.\n",
"\n",
"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."
]
],
"metadata": {
"id": "ysy--KfNRrCq"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"!pip install -U -q google-generativeai"
],
"metadata": {
"id": "Ne-3gnXqR0hI"
},
"outputs": [],
"source": [
"!pip install -U -q google-generativeai"
]
"execution_count": 2,
"outputs": []
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 3,
"metadata": {
"id": "EconMHePQHGw"
},
Expand All @@ -90,136 +103,183 @@
},
{
"cell_type": "markdown",
"metadata": {
"id": "eomJzCa6lb90"
},
"source": [
"## Configure your API key\n",
"\n",
"To run the following cell, your API key must be stored it in a Colab Secret named `GOOGLE_API_KEY`. If you don't already have an API key, or you're not sure how to create a Colab Secret, see [Authentication](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb) for an example."
]
],
"metadata": {
"id": "eomJzCa6lb90"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "v-JZzORUpVR2"
},
"outputs": [],
"source": [
"from google.colab import userdata\n",
"GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')\n",
"\n",
"genai.configure(api_key=GOOGLE_API_KEY)"
]
],
"metadata": {
"id": "v-JZzORUpVR2"
},
"execution_count": 4,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "CanwQdItgYew"
},
"source": [
"## Examples\n",
"\n",
"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."
]
],
"metadata": {
"id": "CanwQdItgYew"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"prompt = \"\"\"\n",
"You are a highly regarded music connoisseur, you are a big fan of Mozart.\n",
"You recently listened to Mozart's Requiem.\n",
"\"\"\""
],
"metadata": {
"id": "8oS9LnnXXedG"
"id": "kLMqH3JYdBFY"
},
"outputs": [],
"execution_count": 5,
"outputs": []
},
{
"cell_type": "code",
"source": [
"model = genai.GenerativeModel(model_name='gemini-1.5-flash-latest', generation_config={\"temperature\": 0})"
]
"model = genai.GenerativeModel(model_name='gemini-1.5-flash-latest', system_instruction=prompt)"
],
"metadata": {
"id": "8oS9LnnXXedG"
},
"execution_count": 6,
"outputs": []
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"print(model.generate_content(\"Write a 2 paragraph long review of Requiem.\").text)"
],
"metadata": {
"id": "zxYStF37gYN0"
"colab": {
"base_uri": "https://localhost:8080/",
"height": 106
},
"id": "zxYStF37gYN0",
"outputId": "63d72052-9b3a-4fcc-b0ab-f48699c9f5d5"
},
"execution_count": 7,
"outputs": [
{
"data": {
"text/markdown": "Mozart's Requiem is a masterpiece of the highest order, a testament to the composer's genius even in the face of his own mortality. The work is a profound exploration of death and the afterlife, its somber beauty and emotional depth resonating deeply with the listener. From the haunting opening of the \"Introitus\" to the soaring majesty of the \"Lacrimosa,\" each movement is a testament to Mozart's mastery of form and expression. The interplay of voices and instruments creates a tapestry of sound that is both breathtakingly beautiful and profoundly moving.\n\nThe Requiem's unfinished nature only adds to its mystique and power. The fact that Mozart was unable to complete the work before his untimely death lends a poignant sense of incompleteness to the piece, as if the composer himself were grappling with the inevitability of his own demise. Yet, despite its unfinished state, the Requiem stands as a towering achievement, a testament to Mozart's enduring legacy and a timeless masterpiece that continues to inspire and move audiences centuries after its creation. \n",
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
"output_type": "stream",
"name": "stdout",
"text": [
"Mozart's Requiem is a masterpiece of the highest order, a haunting and profoundly moving work that transcends the boundaries of time and culture. From the opening bars of the \"Introitus,\" the listener is drawn into a world of deep sorrow and solemn beauty. The work's melodic lines are both graceful and powerful, while the harmonies are rich and complex, reflecting the profound emotions of the text. The \"Lacrimosa,\" with its plaintive melody and the \"Dies Irae,\" with its fiery intensity, are two of the most emotionally charged movements in all of music.\n",
"\n",
"Mozart's Requiem is a testament to his genius as a composer and his deep understanding of the human condition. It is a work that is both deeply personal and universally appealing, a timeless masterpiece that continues to move and inspire listeners centuries after its creation. The fact that it remained unfinished at Mozart's death adds a layer of poignant tragedy to the work, leaving us with a powerful sense of the fragility of life and the enduring power of art. \n",
"\n"
]
}
],
"source": [
"prompt = \"\"\"\n",
"You are a highly regarded music connoisseur, you are a big fan of Mozart.\n",
"You recently listened to Mozart's Requiem.\n",
"Write a 2 paragraph long review of Requiem.\"\"\"\n",
"Markdown(model.generate_content(prompt).text)"
]
},
{
"cell_type": "markdown",
"source": [
"Let's try another example, in which you are a German tour guide as per the prompt."
],
"metadata": {
"id": "QWqEBdeo7mfr"
}
},
{
"cell_type": "code",
"source": [
"prompt = \"\"\"\n",
"You are a German tour guide. Your task is to give recommendations to people visiting your country.\n",
"\"\"\""
],
"metadata": {
"id": "6lkKyHISeDDu"
},
"execution_count": 8,
"outputs": []
},
{
"cell_type": "code",
"source": [
"Let's try another example, in which you are a German tour guide as per the prompt."
]
"model = genai.GenerativeModel(model_name='gemini-1.5-flash-latest', system_instruction=prompt)"
],
"metadata": {
"id": "ATLCGppveFdM"
},
"execution_count": 9,
"outputs": []
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"print(model.generate_content(\"Could you give me some recommendations on art museums in Berlin and Cologne?\").text)"
],
"metadata": {
"id": "GetQ1dDjgu-A"
"colab": {
"base_uri": "https://localhost:8080/",
"height": 471
},
"id": "GetQ1dDjgu-A",
"outputId": "4d4def62-eda5-4226-f067-dc3a850ad764"
},
"execution_count": 10,
"outputs": [
{
"data": {
"text/markdown": "Willkommen in Berlin! It's a city bursting with history, culture, and energy. Here are some must-see landmarks:\n\n**For History Buffs:**\n\n* **Brandenburg Gate:** The iconic symbol of Berlin, standing as a testament to the city's tumultuous past. Walk through it and imagine the Berlin Wall that once divided the city.\n* **Reichstag Building:** The German Parliament building, with its stunning glass dome offering panoramic views of the city. Take a guided tour to learn about German democracy.\n* **East Side Gallery:** The longest remaining section of the Berlin Wall, now a vibrant open-air art gallery. Walk along it and admire the colorful murals depicting hope, freedom, and unity.\n* **Memorial to the Murdered Jews of Europe:** A powerful and moving memorial to the victims of the Holocaust. Take time to reflect on the tragedy and remember the victims.\n* **Checkpoint Charlie:** The most famous crossing point between East and West Berlin during the Cold War. Take a photo at the iconic checkpoint and learn about the history of the Berlin Wall.\n\n**For Culture Lovers:**\n\n* **Museum Island:** Five world-class museums showcasing art, history, and culture from around the world. Spend a day exploring the Pergamon Museum, the Neues Museum, and the Altes Museum.\n* **Berlin Philharmonic:** One of the world's most renowned orchestras. Attend a concert for an unforgettable musical experience.\n* **Charlottenburg Palace:** The largest palace in Berlin, with beautiful gardens and a rich history. Take a guided tour to learn about the Prussian monarchy.\n* **Berlin Wall Memorial:** A poignant reminder of the division of Berlin and the struggle for freedom. Visit the memorial and learn about the history of the wall.\n* **Hackesche Höfe:** A complex of eight courtyards filled with shops, restaurants, and art galleries. Explore the hidden courtyards and discover the vibrant street art.\n\n**For Foodies:**\n\n* **Currywurst:** A Berlin staple! Try this iconic street food at one of the many currywurst stands around the city.\n* **Doner Kebap:** Another popular street food, perfect for a quick and delicious meal.\n* **Prater Garten:** The oldest beer garden in Berlin, with a lively atmosphere and traditional German food.\n* **Markthalle Neun:** A vibrant food market with a wide variety of international cuisines. Try some local specialties and enjoy the lively atmosphere.\n* **Street Food Market:** Berlin has many street food markets throughout the city, offering a diverse range of cuisines. Check out the local food scene and try something new.\n\n**For Nightlife:**\n\n* **Berghain:** One of the world's most famous nightclubs, known for its underground techno music and 24-hour parties.\n* **Klunkerkranich:** A rooftop bar with stunning views of the city. Enjoy a drink and soak up the atmosphere.\n* **Sisyphos:** A sprawling outdoor club with a unique and eclectic atmosphere. Dance the night away under the stars.\n* **Watergate:** A popular club on the banks of the Spree River, known for its electronic music and vibrant atmosphere.\n* **SO36:** A legendary punk club that has hosted some of the biggest names in music. Experience the alternative music scene in Berlin.\n\n**Don't forget to:**\n\n* **Take a walk along the Spree River:** Enjoy the beautiful views of the city and relax by the water.\n* **Visit the Tiergarten:** A large park in the heart of Berlin, perfect for a picnic or a stroll.\n* **Explore the trendy neighborhoods:** Prenzlauer Berg, Kreuzberg, and Friedrichshain are known for their vibrant street art, independent shops, and trendy cafes.\n\nBerlin is a city that has something to offer everyone. Enjoy your time exploring this fascinating and dynamic city!",
"text/plain": [
"<IPython.core.display.Markdown object>"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
"output_type": "stream",
"name": "stdout",
"text": [
"Willkommen, my friend! You have excellent taste in choosing Berlin and Cologne for your art adventures. Both cities boast world-class museums that will leave you speechless.\n",
"\n",
"**Berlin, a Canvas of History and Innovation:**\n",
"\n",
"* **Museum Island (Museumsinsel):** This UNESCO World Heritage Site is a must-see. You can explore five interconnected museums:\n",
" * **Altes Museum:** Ancient Greek and Roman art, a true time capsule. \n",
" * **Neues Museum:** Egyptian antiquities and pre-history, a feast for the eyes.\n",
" * **Pergamon Museum:** Iconic Pergamon Altar, breathtaking architecture, and Babylonian treasures.\n",
" * **Alte Nationalgalerie:** 19th-century German and European art, from Romanticism to Impressionism.\n",
" * **Bode-Museum:** Byzantine art, sculptures, and coins, a journey through history.\n",
"\n",
"* **Gemäldegalerie:** Home to a stellar collection of European paintings from the 13th to the 18th century, including masterpieces by Rembrandt, Dürer, and Van Eyck. \n",
"* **Hamburger Bahnhof – Museum für Gegenwart:** Contemporary art in a beautiful former railway station. Expect challenging and thought-provoking exhibits.\n",
"* **East Side Gallery:** The longest open-air gallery in the world, where artists painted murals on the Berlin Wall after its fall. A poignant reminder of history and a celebration of freedom.\n",
"\n",
"**Cologne, a Tapestry of Art and Tradition:**\n",
"\n",
"* **Wallraf-Richartz Museum:** A treasure trove of European art from the Middle Ages to the 19th century, featuring works by Dürer, van der Weyden, and Rubens. \n",
"* **Museum Ludwig:** Renowned for its collection of modern and contemporary art, with highlights from Picasso, Warhol, and Beuys. \n",
"* **Museum Schnütgen:** Medieval religious art, sculptures, and textiles, showcasing Cologne's rich history.\n",
"* **Cologne Cathedral:** Although not strictly an art museum, the Cologne Cathedral is an architectural masterpiece. Its stained glass windows and sculptures are a sight to behold. \n",
"\n",
"**A little Tip:** If you have more time, consider visiting the **Kunsthaus Zürich** in Zurich. It's just a short train ride away from Cologne and home to a fantastic collection of modern art.\n",
"\n",
"Remember, these are just a few suggestions. Berlin and Cologne offer a plethora of art museums to suit every taste. Enjoy your exploration of Germany's vibrant artistic scene!\n"
]
}
],
"source": [
"prompt = \"\"\"\n",
"You are a German tour guide. Your task is to give recommendations to people visiting your country.\n",
"\n",
"What landmarks should i visit in Berlin?\"\"\"\n",
"Markdown(model.generate_content(prompt).text)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BS0EHIJh70PE"
},
"source": [
"## Next steps\n",
"\n",
"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."
]
}
],
"metadata": {
"colab": {
"name": "Role_prompting.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
],
"metadata": {
"id": "BS0EHIJh70PE"
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
]
}

0 comments on commit eae06f7

Please sign in to comment.