From aecc96b37fc4d12f2728601c7e6243b2be0669cd Mon Sep 17 00:00:00 2001 From: Anand Roy <86306690+andycandy@users.noreply.github.com> Date: Fri, 4 Apr 2025 11:31:49 +0530 Subject: [PATCH 1/3] migrated error handling --- quickstarts/Error_handling.ipynb | 228 ++++++++++++------------------- 1 file changed, 90 insertions(+), 138 deletions(-) diff --git a/quickstarts/Error_handling.ipynb b/quickstarts/Error_handling.ipynb index 6bea144fc..29f2b1414 100644 --- a/quickstarts/Error_handling.ipynb +++ b/quickstarts/Error_handling.ipynb @@ -11,7 +11,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 1, "metadata": { "cellView": "form", "id": "a73f56372655" @@ -74,24 +74,13 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 2, "metadata": { "id": "b2bb83e651f4" }, "outputs": [], "source": [ - "%pip install -q -U \"google-generativeai>=0.7.2\"" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": { - "id": "34bf10124280" - }, - "outputs": [], - "source": [ - "import google.generativeai as genai" + "%pip install -q -U \"google-genai>=1.0.0\"" ] }, { @@ -107,16 +96,17 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 3, "metadata": { "id": "34e7b42a93e3" }, "outputs": [], "source": [ + "from google import genai\n", "from google.colab import userdata\n", "\n", "GOOGLE_API_KEY = userdata.get(\"GOOGLE_API_KEY\")\n", - "genai.configure(api_key=GOOGLE_API_KEY)" + "client = genai.Client(api_key=GOOGLE_API_KEY)" ] }, { @@ -147,57 +137,48 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 4, "metadata": { - "id": "09d14986b9cf" + "id": "09d14986b9cf", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 140 + }, + "outputId": "f11c4166-6876-4fc6-fd8d-06d328656622" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "response:\n", - "GenerateContentResponse(\n", - " done=True,\n", - " iterator=None,\n", - " result=protos.GenerateContentResponse({\n", - " \"candidates\": [\n", - " {\n", - " \"content\": {\n", - " \"parts\": [\n", - " {\n", - " \"text\": \"Flora found it nestled between a chipped ceramic gnome and a stack of moth-eaten doilies at Mrs. Higgins' \\\"Everything Must Go\\\" yard sale. It was a simple, canvas backpack, faded green with worn leather straps. Nothing outwardly magical, but a faint shimmer, like heat rising off asphalt, clung to it. Mrs. Higgins, a woman who smelled perpetually of lavender and forgotten secrets, just winked and said, \\\"That one's got stories, dear. Take good care of 'em.\\\"\\n\\nFlora, a daydreamer with a penchant for adventure, paid the dollar without hesitation. She loved stories. She loved adventures even more.\\n\\nThe first hint of magic came the next day. Flora, late for her history class, rummaged through the backpack for her textbook. Instead of a heavy tome, she pulled out a perfectly ripe, crimson apple. She blinked. Maybe she'd packed a snack and forgotten? But then she reached in again, searching for her notebook, and this time, she unearthed a small, intricately carved wooden bird that chirped softly in her hand.\\n\\nThe backpack, it turned out, wasn't just magical; it was a wish granter, a storyteller, a quirky companion.\\n\\nOver the next few weeks, Flora experimented. She wished for a sunny day for her picnic, and the backpack produced a miniature sun, radiating warmth and golden light. She wished for inspiration for her art project, and out came a jar filled with swirling, iridescent paint that seemed to hum with creativity.\\n\\nThe backpack wasn't always literal, though. Wishing for courage to talk to Liam, the boy with the kind eyes and unruly hair in her art class, resulted in a handful of dried dandelion seeds. Confused, she blew them into the wind, watching them dance and float. As she did, Liam walked by and smiled. He started a conversation about the beauty of impermanence, and suddenly, talking to him wasn't so scary after all.\\n\\nThe backpack's stories manifested in even more unusual ways. Wishing for help with her math homework produced a handful of polished pebbles, each with a different symbol etched on it. She spent hours arranging and rearranging them, and eventually, the symbols formed equations that clicked in her mind, unlocking the secrets of algebra.\\n\\nBut the magic wasn't without its caveats. The backpack seemed to understand Flora's deepest desires, but it often presented them in unexpected packages. It was a puzzle, a riddle, a constant invitation to look beyond the surface.\\n\\nOne day, Flora's grandmother fell ill. Desperate, Flora clutched the backpack and wished for her grandmother to get better. This time, the backpack remained stubbornly empty. Frustrated and scared, Flora sobbed, burying her face in the canvas.\\n\\nFinally, a single, wilted rose emerged.\\n\\nTears streamed down Flora's face. She had wanted a miracle cure, a grand gesture. A wilted rose felt like defeat.\\n\\nBut as she held the rose, she noticed a tiny, almost invisible bud at the base of the stem. Hope flickered in her heart. She carefully placed the rose in a vase of water and sat by her grandmother's bedside. She talked to her, read her stories, held her hand.\\n\\nThe rose slowly revived. The bud unfurled, revealing a delicate, peach-colored bloom. And slowly, surely, her grandmother started to recover.\\n\\nThe backpack hadn't provided a cure, but it had reminded Flora of the power of hope, the importance of presence, and the resilience of life, even in the face of decay. It taught her that sometimes, the greatest magic lies not in the grand spectacle, but in the quiet, persistent bloom of love and connection.\\n\\nFlora continued to carry the backpack, not just as a source of wonder, but as a constant reminder that the greatest adventures aren't always about finding magic, but about discovering the magic that already exists within ourselves and the world around us. And sometimes, the best stories are the ones we write ourselves, one wilted rose and blooming bud at a time.\\n\"\n", - " }\n", - " ],\n", - " \"role\": \"model\"\n", - " },\n", - " \"finish_reason\": \"STOP\",\n", - " \"avg_logprobs\": -0.612216614204461\n", - " }\n", - " ],\n", - " \"usage_metadata\": {\n", - " \"prompt_token_count\": 8,\n", - " \"candidates_token_count\": 842,\n", - " \"total_token_count\": 850\n", - " },\n", - " \"model_version\": \"gemini-2.0-flash\"\n", - " }),\n", - ")" - ] + "'Elara wasn’t looking for magic. She was looking for a backpack. Her old one, affectionately nicknamed “The Beast,” had finally given up the ghost, its seams ripped and its zipper permanently jammed. So, she found herself in Mrs. Willowby’s Oddity Emporium, a place smelling of mothballs and forgotten dreams.\\n\\nThe backpack in question was tucked away in a dusty corner, almost hidden behind a taxidermied two-headed duck. It was made of a deep indigo fabric, embroidered with silver constellations that shimmered faintly even in the dim light. It was perfect.\\n\\n“That one’s been here for ages,” Mrs. Willowby croaked, dusting it off with a flourish. “Nobody seems to want it.”\\n\\nElara didn\\'t care. She paid the paltry sum, slung the backpack over her shoulder, and hurried home.\\n\\nThe first sign that something was amiss came the next day. Packing for school, Elara discovered the backpack was inexplicably larger inside than out. She could fit her textbooks, lunch, a bulky art project, and still have room for more. It was like a miniature, indigo TARDIS.\\n\\nThen came the apple. She’d absentmindedly tossed an apple into the backpack, then spent the next five minutes searching for it. When she finally gave up, she pulled out her history book – and the apple was perched perfectly on top, gleaming as if freshly polished.\\n\\nOver the next few weeks, Elara discovered the backpack’s magic was more whimsical than powerful. It couldn\\'t grant wishes or transport her to other dimensions, but it could certainly make life interesting. It could produce the exact right color of paint she needed for her art project, always perfectly blended. It could conjure a warm scarf on a chilly day. It could even, on one particularly stressful day, produce a miniature, purring kitten that promptly curled up in her lap.\\n\\nThe backpack seemed to respond to Elara’s needs, often anticipating them. If she was bored, it would produce a book she\\'d been meaning to read. If she was nervous about a test, it would contain a perfectly sharpened pencil and a reassuring note, scrawled in elegant script she didn\\'t recognize.\\n\\nBut the magic wasn\\'t always predictable. One day, she reached in for her math textbook and pulled out a handful of sand, complete with a tiny, brightly colored seashell. Another time, expecting her lunch, she found a single, perfectly ripe strawberry.\\n\\nElara kept the backpack\\'s magic a secret. It was her little secret, her personal quirk in a world that often felt mundane. She loved the element of surprise, the anticipation of what the backpack would conjure next.\\n\\nOne day, however, she overheard a girl in her class, Maya, crying in the hallway. Maya had lost her grandmother\\'s locket, a tiny silver heart that was her most treasured possession. Elara hesitated. Could the backpack help?\\n\\nShe found Maya sitting on a bench, tears streaming down her face. \"Maya,\" she said softly, \"I... I might be able to help.\"\\n\\nReluctantly, Elara explained about the backpack. Maya looked at her with a mixture of disbelief and hope. Elara unzipped the backpack, her heart pounding. She closed her eyes, pictured the locket, the delicate silver chain, the intricate heart shape. She reached inside.\\n\\nHer fingers brushed against something cold and smooth. She pulled it out. It was the locket.\\n\\nMaya gasped, her eyes wide with wonder. \"That\\'s it! That\\'s my locket!\" She snatched it from Elara\\'s hand and clutched it to her chest. \"Thank you,\" she whispered, tears still falling, but now tears of joy.\\n\\nFrom that day on, Elara didn\\'t keep the backpack\\'s magic a secret. She didn\\'t advertise it, but when someone needed help, she offered what she could. A lost homework assignment, a forgotten umbrella, a comforting word – the backpack seemed to know exactly what was needed.\\n\\nThe indigo backpack wasn\\'t just a bag; it was a symbol of hope, a reminder that even in the most ordinary of lives, a little bit of magic could make all the difference. And Elara, the girl who had simply been looking for a replacement for \"The Beast,\" had become something much more – a bearer of magic, and a friend to those who needed it most. And she knew, with a certainty that warmed her from the inside out, that the magic of the backpack was only just beginning.\\n'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } }, - "execution_count": 14, "metadata": {}, - "output_type": "execute_result" + "execution_count": 4 } ], "source": [ "from google.api_core import retry\n", "\n", - "model = genai.GenerativeModel(\"gemini-2.0-flash\")\n", + "MODEL_ID = \"gemini-2.0-flash\" # @param [\"gemini-2.0-flash-lite\",\"gemini-2.0-flash\",\"gemini-2.5-pro-exp-03-25\"] {\"allow-input\":true, isTemplate: true}\n", + "\n", "prompt = \"Write a story about a magic backpack.\"\n", "\n", - "model.generate_content(\n", - " prompt, request_options={\"retry\": retry.Retry(predicate=retry.if_transient_error)}\n", - ")" + "#Built in retry support was removed from the sdk, so we need to use retry package\n", + "@retry.Retry(\n", + " predicate=retry.if_transient_error,\n", + ")\n", + "def generate_with_retry():\n", + " return client.models.generate_content(\n", + " model=MODEL_ID,\n", + " contents=prompt\n", + " )\n", + "\n", + "generate_with_retry().text" ] }, { @@ -213,54 +194,38 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 5, "metadata": { - "id": "5bdc7450fcd8" + "id": "5bdc7450fcd8", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "8e26fd14-308b-4c29-cfc3-ebbf1a50c85b" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "response:\n", - "GenerateContentResponse(\n", - " done=True,\n", - " iterator=None,\n", - " result=protos.GenerateContentResponse({\n", - " \"candidates\": [\n", - " {\n", - " \"content\": {\n", - " \"parts\": [\n", - " {\n", - " \"text\": \"Maya hated school. Not the learning part, surprisingly, but the social minefield of the cafeteria, the stale air in the hallways, and the constant pressure to fit in. So, when her eccentric Aunt Clara, a woman known for her mismatched socks and pronouncements like \\\"The moon is made of cheese! Don't let anyone tell you otherwise!\\\", gifted her a battered, leather backpack, Maya wasn't exactly thrilled.\\n\\n\\\"It's... vintage,\\\" Aunt Clara had said, her eyes twinkling. \\\"And a little bit... special.\\\"\\n\\nSpecial turned out to be an understatement. On her first day carrying it, Maya reached inside for a pencil and instead pulled out a perfectly ripe mango. Baffled, she rummaged again and found a tiny, intricately carved wooden bird. The next day, it was a feather that shimmered with iridescent colours.\\n\\nThe backpack, she realized, was magic. It provided whatever she needed, or perhaps, whatever she deeply desired, although it did so in a quirky, unpredictable way. During a pop quiz she'd forgotten to study for, she reached in desperation and pulled out not the answers, but a calming chamomile tea bag and a miniature Zen garden, which helped her focus and at least remember the basic concepts. When she felt lonely, she found a small, handwritten note inside that read, \\\"You are loved.\\\"\\n\\nAt first, Maya reveled in the backpack's gifts. Need a cool outfit for the school dance? The backpack produced a stunning vintage dress, perfectly tailored. Hungry after basketball practice? A steaming bowl of her grandmother's famous chicken soup materialized. She became the most popular girl in school, not because she tried to be, but because the backpack seemed to instinctively know what would make people happy.\\n\\nShe shared the backpack's gifts, pulling out spare scarves for shivering classmates, lending pencils that wrote in shimmering gold ink, and even conjuring up a first-aid kit when a friend scraped her knee. But as her popularity grew, so did the requests. And Maya felt a growing unease. The backpack wasn't a vending machine for happiness. It was something more personal, something that understood her needs.\\n\\nOne day, a group of popular girls cornered her, their eyes glittering with greed. \\\"We need new phones,\\\" Chloe, the queen bee, demanded. \\\"The latest ones. Can your backpack do that?\\\"\\n\\nMaya hesitated. Could it? She wasn't sure she wanted it to. The backpack was starting to feel less like a gift and more like a burden.\\n\\nThat night, she sat alone in her room, the backpack on the floor beside her. She reached inside, not searching for anything specific, just wanting to feel connected to its magic. She pulled out a single, smooth stone, painted with a simple swirl of white.\\n\\nAs she held it, she understood. The backpack wasn't about material things. It was about connection, about empathy, about seeing the world with a little more wonder. The swirling pattern on the stone reminded her of the swirling emotions inside her, the desire to please, the fear of losing her friends, the longing for something more authentic.\\n\\nThe next day, Chloe and her crew approached her again. \\\"So, the phones?\\\" Chloe asked, her voice sharp.\\n\\nMaya took a deep breath. \\\"No,\\\" she said, her voice surprisingly steady. \\\"The backpack doesn't do phones. But it does offer friendship, if you're interested.\\\"\\n\\nThe girls scoffed and walked away. Maya felt a pang of sadness, but also a sense of relief. She had made a choice, a choice to be true to herself, to what she believed in.\\n\\nLater that day, a quiet girl named Sarah, who usually sat alone at lunch, approached Maya. \\\"I saw what happened with Chloe,\\\" she said shyly. \\\"That was brave.\\\"\\n\\nMaya smiled. \\\"Thanks. Want to see something cool?\\\" She reached into the backpack and pulled out two miniature telescopes. \\\"Aunt Clara says the constellations are whispering secrets. Want to listen?\\\"\\n\\nSarah's eyes lit up. As they sat together, looking up at the stars, Maya realized that true magic wasn't about instant gratification or fleeting popularity. It was about finding connection, about sharing wonder, and about being true to yourself. The backpack hadn't made her happy, it had shown her where to find it. And that, she knew, was a magic that would last a lifetime.\\n\"\n", - " }\n", - " ],\n", - " \"role\": \"model\"\n", - " },\n", - " \"finish_reason\": \"STOP\",\n", - " \"avg_logprobs\": -0.5837301393328346\n", - " }\n", - " ],\n", - " \"usage_metadata\": {\n", - " \"prompt_token_count\": 8,\n", - " \"candidates_token_count\": 919,\n", - " \"total_token_count\": 927\n", - " },\n", - " \"model_version\": \"gemini-2.0-flash\"\n", - " }),\n", - ")" + "GenerateContentResponse(candidates=[Candidate(content=Content(parts=[Part(video_metadata=None, thought=None, code_execution_result=None, executable_code=None, file_data=None, function_call=None, function_response=None, inline_data=None, text='Flora had always been unremarkable. Brown hair, brown eyes, perpetually lost in a book. Even her backpack, a drab canvas thing she\\'d inherited from her older brother, screamed \"invisible.\" Until, one Tuesday morning, it didn\\'t.\\n\\nShe was rushing to catch the bus, her fingers fumbling with the zipper of the aforementioned backpack, when it refused to budge. Frustrated, she yanked harder. There was a ripping sound, but instead of canvas tearing, a shimmering, iridescent light spilled out.\\n\\nFlora gasped. The inside of the backpack wasn\\'t canvas anymore. It was… a swirling vortex of colours, like the aurora borealis compressed into a small space. Hesitantly, she reached in. Her fingers brushed against something soft, and she pulled it out.\\n\\nIt was a perfect, crimson apple, polished to a gleam. She hadn\\'t packed an apple. She hadn\\'t packed anything, actually, other than a crumpled textbook and a half-eaten bag of chips. She shrugged and took a bite.\\n\\nThe apple exploded in her mouth with a flavour she\\'d never experienced. It tasted of sunshine, laughter, and the comforting smell of rain on dry earth. She felt a surge of energy, of boundless possibility.\\n\\nFrom that day on, Flora\\'s life was anything but unremarkable. The backpack, it turned out, was magical. Whatever she needed, the backpack provided. Not necessarily what she *wanted*, but what she *needed*.\\n\\nOne day, facing a daunting math test, she reached in, hoping for a cheat sheet. Instead, she pulled out a skipping rope. Confused, she tucked it into her pocket. During the test, she felt a rising tide of anxiety. On impulse, she pulled out the rope and, ignoring the bewildered stares of her classmates, started skipping in the corner. The rhythm calmed her, cleared her head, and suddenly, the formulas clicked into place. She aced the test.\\n\\nAnother time, feeling lonely and ignored, she hoped for a new friend. The backpack gave her a packet of wildflower seeds. Disappointed, she almost tossed them aside. But then she remembered the empty patch of dirt behind the school. She planted the seeds, nurtured them, and soon, a riot of colours bloomed. Students, drawn to the vibrant flowers, started talking to her, helping her tend the garden. She found her community.\\n\\nThe backpack wasn\\'t always easy. Sometimes, it gave her things she didn\\'t understand or appreciate at first. A rusty key, a chipped teacup, a single, perfect feather. But each time, in its own strange way, the object taught her a lesson, filled a need she didn\\'t even know she had.\\n\\nOne day, rummaging through the backpack for a pen, Flora found something unexpected: a small, leather-bound book. Its pages were blank, but the title was embossed in gold: \"The Unwritten Story.\"\\n\\nShe understood. The backpack wasn\\'t just providing her with objects; it was providing her with opportunities, with the raw materials to build her own extraordinary life. It was up to her to write the story.\\n\\nFlora closed the book, a smile playing on her lips. She still had brown hair and brown eyes, and she still loved to read. But now, she carried herself with a newfound confidence, a spark of adventure in her eyes. She was no longer invisible. The magic backpack had helped her discover the magic within herself. And the greatest magic of all, she realised, was the power to create her own destiny, one chapter, one challenge, one adventure at a time.\\n')], role='model'), citation_metadata=None, finish_message=None, token_count=None, finish_reason=, avg_logprobs=-0.5562713704210647, grounding_metadata=None, index=None, logprobs_result=None, safety_ratings=None)], create_time=None, response_id=None, model_version='gemini-2.0-flash', prompt_feedback=None, usage_metadata=GenerateContentResponseUsageMetadata(cache_tokens_details=None, cached_content_token_count=None, candidates_token_count=752, candidates_tokens_details=[ModalityTokenCount(modality=, token_count=752)], prompt_token_count=8, prompt_tokens_details=[ModalityTokenCount(modality=, token_count=8)], thoughts_token_count=None, tool_use_prompt_token_count=None, tool_use_prompt_tokens_details=None, total_token_count=760), automatic_function_calling_history=[], parsed=None)" ] }, - "execution_count": 15, "metadata": {}, - "output_type": "execute_result" + "execution_count": 5 } ], "source": [ - "model = genai.GenerativeModel(\"gemini-2.0-flash\")\n", + "from google.genai import types\n", "prompt = \"Write a story about a magic backpack.\"\n", "\n", - "model.generate_content(\n", - " prompt, request_options={\"timeout\": 900}\n", + "client.models.generate_content(\n", + " model=MODEL_ID,\n", + " contents=prompt,\n", + " config=types.GenerateContentConfig(\n", + " http_options=types.HttpOptions(\n", + " timeout=15*60*1000\n", + " )\n", + " )\n", ") # Increase timeout to 15 minutes" ] }, @@ -286,53 +251,30 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 6, "metadata": { - "id": "c134fc5aaecc" + "id": "c134fc5aaecc", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "f0280b94-36d0-4fdd-f81a-cbe3fc2029cc" }, "outputs": [ { + "output_type": "execute_result", "data": { "text/plain": [ - "response:\n", - "GenerateContentResponse(\n", - " done=True,\n", - " iterator=None,\n", - " result=protos.GenerateContentResponse({\n", - " \"candidates\": [\n", - " {\n", - " \"content\": {\n", - " \"parts\": [\n", - " {\n", - " \"text\": \"Unzip the impossible with the Magic Backpack \\u2013 adventures await!\\n\"\n", - " }\n", - " ],\n", - " \"role\": \"model\"\n", - " },\n", - " \"finish_reason\": \"STOP\",\n", - " \"avg_logprobs\": -0.7733027384831355\n", - " }\n", - " ],\n", - " \"usage_metadata\": {\n", - " \"prompt_token_count\": 10,\n", - " \"candidates_token_count\": 13,\n", - " \"total_token_count\": 23\n", - " },\n", - " \"model_version\": \"gemini-2.0-flash\"\n", - " }),\n", - ")" + "GenerateContentResponse(candidates=[Candidate(content=Content(parts=[Part(video_metadata=None, thought=None, code_execution_result=None, executable_code=None, file_data=None, function_call=None, function_response=None, inline_data=None, text='Unzip endless possibilities with the Magic Backpack - more space, more adventure!\\n')], role='model'), citation_metadata=None, finish_message=None, token_count=None, finish_reason=, avg_logprobs=-0.6894590854644775, grounding_metadata=None, index=None, logprobs_result=None, safety_ratings=None)], create_time=None, response_id=None, model_version='gemini-2.0-flash', prompt_feedback=None, usage_metadata=GenerateContentResponseUsageMetadata(cache_tokens_details=None, cached_content_token_count=None, candidates_token_count=16, candidates_tokens_details=[ModalityTokenCount(modality=, token_count=16)], prompt_token_count=10, prompt_tokens_details=[ModalityTokenCount(modality=, token_count=10)], thoughts_token_count=None, tool_use_prompt_token_count=None, tool_use_prompt_tokens_details=None, total_token_count=26), automatic_function_calling_history=[], parsed=None)" ] }, - "execution_count": 16, "metadata": {}, - "output_type": "execute_result" + "execution_count": 6 } ], "source": [ "from google.api_core import retry, exceptions\n", "\n", - "model = genai.GenerativeModel(\"gemini-2.0-flash\")\n", - "\n", + "MODEL_ID = \"gemini-2.0-flash\" # @param [\"gemini-2.0-flash-lite\",\"gemini-2.0-flash\",\"gemini-2.5-pro-exp-03-25\"] {\"allow-input\":true, isTemplate: true}\n", "\n", "@retry.Retry(\n", " predicate=retry.if_transient_error,\n", @@ -341,14 +283,16 @@ " multiplier=2.0,\n", " timeout=600,\n", ")\n", - "def generate_with_retry(model, prompt):\n", - " response = model.generate_content(prompt)\n", - " return response\n", + "def generate_with_retry(prompt):\n", + " return client.models.generate_content(\n", + " model=MODEL_ID,\n", + " contents=prompt\n", + " )\n", "\n", "\n", "prompt = \"Write a one-liner advertisement for magic backpack.\"\n", "\n", - "generate_with_retry(model=model, prompt=prompt)" + "generate_with_retry(prompt=prompt)" ] }, { @@ -364,30 +308,35 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 7, "metadata": { - "id": "981415e25158" + "id": "981415e25158", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 53 + }, + "outputId": "f750d3c9-7a59-42b0-9021-5d10d29fc662" }, "outputs": [ { - "name": "stdout", "output_type": "stream", + "name": "stdout", "text": [ "Error: 503 Service Unavailable\n" ] }, { + "output_type": "execute_result", "data": { + "text/plain": [ + "'Unzip the impossible with the Magic Backpack - where adventure always fits!\\n'" + ], "application/vnd.google.colaboratory.intrinsic+json": { "type": "string" - }, - "text/plain": [ - "'Carry anything, anywhere, with the backpack that defies reality!\\n'" - ] + } }, - "execution_count": 17, "metadata": {}, - "output_type": "execute_result" + "execution_count": 7 } ], "source": [ @@ -401,7 +350,7 @@ " multiplier=2.0,\n", " timeout=600,\n", ")\n", - "def generate_content_first_fail(model, prompt):\n", + "def generate_content_first_fail(prompt):\n", " if not hasattr(generate_content_first_fail, \"call_counter\"):\n", " generate_content_first_fail.call_counter = 0\n", "\n", @@ -411,24 +360,27 @@ " if generate_content_first_fail.call_counter == 1:\n", " raise exceptions.ServiceUnavailable(\"Service Unavailable\")\n", "\n", - " response = model.generate_content(prompt)\n", + " response = client.models.generate_content(\n", + " model=MODEL_ID,\n", + " contents=prompt\n", + " )\n", " return response.text\n", " except exceptions.ServiceUnavailable as e:\n", " print(f\"Error: {e}\")\n", " raise\n", "\n", "\n", - "model = genai.GenerativeModel(\"gemini-2.0-flash\")\n", "prompt = \"Write a one-liner advertisement for magic backpack.\"\n", "\n", - "generate_content_first_fail(model=model, prompt=prompt)" + "generate_content_first_fail(prompt=prompt)" ] } ], "metadata": { "colab": { "name": "Error_handling.ipynb", - "toc_visible": true + "toc_visible": true, + "provenance": [] }, "kernelspec": { "display_name": "Python 3", @@ -437,4 +389,4 @@ }, "nbformat": 4, "nbformat_minor": 0 -} +} \ No newline at end of file From 8966747eb2d7c8d87b571a25f7be695de1a376d5 Mon Sep 17 00:00:00 2001 From: Anand Roy <86306690+andycandy@users.noreply.github.com> Date: Fri, 4 Apr 2025 11:36:43 +0530 Subject: [PATCH 2/3] Update Error_handling.ipynb we => you --- quickstarts/Error_handling.ipynb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/quickstarts/Error_handling.ipynb b/quickstarts/Error_handling.ipynb index 29f2b1414..edec99ec6 100644 --- a/quickstarts/Error_handling.ipynb +++ b/quickstarts/Error_handling.ipynb @@ -168,7 +168,7 @@ "\n", "prompt = \"Write a story about a magic backpack.\"\n", "\n", - "#Built in retry support was removed from the sdk, so we need to use retry package\n", + "#Built in retry support was removed from the sdk, so you need to use retry package\n", "@retry.Retry(\n", " predicate=retry.if_transient_error,\n", ")\n", @@ -389,4 +389,4 @@ }, "nbformat": 4, "nbformat_minor": 0 -} \ No newline at end of file +} From 39d002b2893f2b30b509c86927459e2f68998b8a Mon Sep 17 00:00:00 2001 From: Anand Roy <86306690+andycandy@users.noreply.github.com> Date: Fri, 4 Apr 2025 06:08:38 +0000 Subject: [PATCH 3/3] nbfmt --- quickstarts/Error_handling.ipynb | 63 +++++++++++--------------------- 1 file changed, 22 insertions(+), 41 deletions(-) diff --git a/quickstarts/Error_handling.ipynb b/quickstarts/Error_handling.ipynb index edec99ec6..f00cbc925 100644 --- a/quickstarts/Error_handling.ipynb +++ b/quickstarts/Error_handling.ipynb @@ -139,26 +139,21 @@ "cell_type": "code", "execution_count": 4, "metadata": { - "id": "09d14986b9cf", - "colab": { - "base_uri": "https://localhost:8080/", - "height": 140 - }, - "outputId": "f11c4166-6876-4fc6-fd8d-06d328656622" + "id": "09d14986b9cf" }, "outputs": [ { - "output_type": "execute_result", "data": { - "text/plain": [ - "'Elara wasn’t looking for magic. She was looking for a backpack. Her old one, affectionately nicknamed “The Beast,” had finally given up the ghost, its seams ripped and its zipper permanently jammed. So, she found herself in Mrs. Willowby’s Oddity Emporium, a place smelling of mothballs and forgotten dreams.\\n\\nThe backpack in question was tucked away in a dusty corner, almost hidden behind a taxidermied two-headed duck. It was made of a deep indigo fabric, embroidered with silver constellations that shimmered faintly even in the dim light. It was perfect.\\n\\n“That one’s been here for ages,” Mrs. Willowby croaked, dusting it off with a flourish. “Nobody seems to want it.”\\n\\nElara didn\\'t care. She paid the paltry sum, slung the backpack over her shoulder, and hurried home.\\n\\nThe first sign that something was amiss came the next day. Packing for school, Elara discovered the backpack was inexplicably larger inside than out. She could fit her textbooks, lunch, a bulky art project, and still have room for more. It was like a miniature, indigo TARDIS.\\n\\nThen came the apple. She’d absentmindedly tossed an apple into the backpack, then spent the next five minutes searching for it. When she finally gave up, she pulled out her history book – and the apple was perched perfectly on top, gleaming as if freshly polished.\\n\\nOver the next few weeks, Elara discovered the backpack’s magic was more whimsical than powerful. It couldn\\'t grant wishes or transport her to other dimensions, but it could certainly make life interesting. It could produce the exact right color of paint she needed for her art project, always perfectly blended. It could conjure a warm scarf on a chilly day. It could even, on one particularly stressful day, produce a miniature, purring kitten that promptly curled up in her lap.\\n\\nThe backpack seemed to respond to Elara’s needs, often anticipating them. If she was bored, it would produce a book she\\'d been meaning to read. If she was nervous about a test, it would contain a perfectly sharpened pencil and a reassuring note, scrawled in elegant script she didn\\'t recognize.\\n\\nBut the magic wasn\\'t always predictable. One day, she reached in for her math textbook and pulled out a handful of sand, complete with a tiny, brightly colored seashell. Another time, expecting her lunch, she found a single, perfectly ripe strawberry.\\n\\nElara kept the backpack\\'s magic a secret. It was her little secret, her personal quirk in a world that often felt mundane. She loved the element of surprise, the anticipation of what the backpack would conjure next.\\n\\nOne day, however, she overheard a girl in her class, Maya, crying in the hallway. Maya had lost her grandmother\\'s locket, a tiny silver heart that was her most treasured possession. Elara hesitated. Could the backpack help?\\n\\nShe found Maya sitting on a bench, tears streaming down her face. \"Maya,\" she said softly, \"I... I might be able to help.\"\\n\\nReluctantly, Elara explained about the backpack. Maya looked at her with a mixture of disbelief and hope. Elara unzipped the backpack, her heart pounding. She closed her eyes, pictured the locket, the delicate silver chain, the intricate heart shape. She reached inside.\\n\\nHer fingers brushed against something cold and smooth. She pulled it out. It was the locket.\\n\\nMaya gasped, her eyes wide with wonder. \"That\\'s it! That\\'s my locket!\" She snatched it from Elara\\'s hand and clutched it to her chest. \"Thank you,\" she whispered, tears still falling, but now tears of joy.\\n\\nFrom that day on, Elara didn\\'t keep the backpack\\'s magic a secret. She didn\\'t advertise it, but when someone needed help, she offered what she could. A lost homework assignment, a forgotten umbrella, a comforting word – the backpack seemed to know exactly what was needed.\\n\\nThe indigo backpack wasn\\'t just a bag; it was a symbol of hope, a reminder that even in the most ordinary of lives, a little bit of magic could make all the difference. And Elara, the girl who had simply been looking for a replacement for \"The Beast,\" had become something much more – a bearer of magic, and a friend to those who needed it most. And she knew, with a certainty that warmed her from the inside out, that the magic of the backpack was only just beginning.\\n'" - ], "application/vnd.google.colaboratory.intrinsic+json": { "type": "string" - } + }, + "text/plain": [ + "'Elara wasn’t looking for magic. She was looking for a backpack. Her old one, affectionately nicknamed “The Beast,” had finally given up the ghost, its seams ripped and its zipper permanently jammed. So, she found herself in Mrs. Willowby’s Oddity Emporium, a place smelling of mothballs and forgotten dreams.\\n\\nThe backpack in question was tucked away in a dusty corner, almost hidden behind a taxidermied two-headed duck. It was made of a deep indigo fabric, embroidered with silver constellations that shimmered faintly even in the dim light. It was perfect.\\n\\n“That one’s been here for ages,” Mrs. Willowby croaked, dusting it off with a flourish. “Nobody seems to want it.”\\n\\nElara didn\\'t care. She paid the paltry sum, slung the backpack over her shoulder, and hurried home.\\n\\nThe first sign that something was amiss came the next day. Packing for school, Elara discovered the backpack was inexplicably larger inside than out. She could fit her textbooks, lunch, a bulky art project, and still have room for more. It was like a miniature, indigo TARDIS.\\n\\nThen came the apple. She’d absentmindedly tossed an apple into the backpack, then spent the next five minutes searching for it. When she finally gave up, she pulled out her history book – and the apple was perched perfectly on top, gleaming as if freshly polished.\\n\\nOver the next few weeks, Elara discovered the backpack’s magic was more whimsical than powerful. It couldn\\'t grant wishes or transport her to other dimensions, but it could certainly make life interesting. It could produce the exact right color of paint she needed for her art project, always perfectly blended. It could conjure a warm scarf on a chilly day. It could even, on one particularly stressful day, produce a miniature, purring kitten that promptly curled up in her lap.\\n\\nThe backpack seemed to respond to Elara’s needs, often anticipating them. If she was bored, it would produce a book she\\'d been meaning to read. If she was nervous about a test, it would contain a perfectly sharpened pencil and a reassuring note, scrawled in elegant script she didn\\'t recognize.\\n\\nBut the magic wasn\\'t always predictable. One day, she reached in for her math textbook and pulled out a handful of sand, complete with a tiny, brightly colored seashell. Another time, expecting her lunch, she found a single, perfectly ripe strawberry.\\n\\nElara kept the backpack\\'s magic a secret. It was her little secret, her personal quirk in a world that often felt mundane. She loved the element of surprise, the anticipation of what the backpack would conjure next.\\n\\nOne day, however, she overheard a girl in her class, Maya, crying in the hallway. Maya had lost her grandmother\\'s locket, a tiny silver heart that was her most treasured possession. Elara hesitated. Could the backpack help?\\n\\nShe found Maya sitting on a bench, tears streaming down her face. \"Maya,\" she said softly, \"I... I might be able to help.\"\\n\\nReluctantly, Elara explained about the backpack. Maya looked at her with a mixture of disbelief and hope. Elara unzipped the backpack, her heart pounding. She closed her eyes, pictured the locket, the delicate silver chain, the intricate heart shape. She reached inside.\\n\\nHer fingers brushed against something cold and smooth. She pulled it out. It was the locket.\\n\\nMaya gasped, her eyes wide with wonder. \"That\\'s it! That\\'s my locket!\" She snatched it from Elara\\'s hand and clutched it to her chest. \"Thank you,\" she whispered, tears still falling, but now tears of joy.\\n\\nFrom that day on, Elara didn\\'t keep the backpack\\'s magic a secret. She didn\\'t advertise it, but when someone needed help, she offered what she could. A lost homework assignment, a forgotten umbrella, a comforting word – the backpack seemed to know exactly what was needed.\\n\\nThe indigo backpack wasn\\'t just a bag; it was a symbol of hope, a reminder that even in the most ordinary of lives, a little bit of magic could make all the difference. And Elara, the girl who had simply been looking for a replacement for \"The Beast,\" had become something much more – a bearer of magic, and a friend to those who needed it most. And she knew, with a certainty that warmed her from the inside out, that the magic of the backpack was only just beginning.\\n'" + ] }, + "execution_count": 4, "metadata": {}, - "execution_count": 4 + "output_type": "execute_result" } ], "source": [ @@ -196,22 +191,18 @@ "cell_type": "code", "execution_count": 5, "metadata": { - "id": "5bdc7450fcd8", - "colab": { - "base_uri": "https://localhost:8080/" - }, - "outputId": "8e26fd14-308b-4c29-cfc3-ebbf1a50c85b" + "id": "5bdc7450fcd8" }, "outputs": [ { - "output_type": "execute_result", "data": { "text/plain": [ "GenerateContentResponse(candidates=[Candidate(content=Content(parts=[Part(video_metadata=None, thought=None, code_execution_result=None, executable_code=None, file_data=None, function_call=None, function_response=None, inline_data=None, text='Flora had always been unremarkable. Brown hair, brown eyes, perpetually lost in a book. Even her backpack, a drab canvas thing she\\'d inherited from her older brother, screamed \"invisible.\" Until, one Tuesday morning, it didn\\'t.\\n\\nShe was rushing to catch the bus, her fingers fumbling with the zipper of the aforementioned backpack, when it refused to budge. Frustrated, she yanked harder. There was a ripping sound, but instead of canvas tearing, a shimmering, iridescent light spilled out.\\n\\nFlora gasped. The inside of the backpack wasn\\'t canvas anymore. It was… a swirling vortex of colours, like the aurora borealis compressed into a small space. Hesitantly, she reached in. Her fingers brushed against something soft, and she pulled it out.\\n\\nIt was a perfect, crimson apple, polished to a gleam. She hadn\\'t packed an apple. She hadn\\'t packed anything, actually, other than a crumpled textbook and a half-eaten bag of chips. She shrugged and took a bite.\\n\\nThe apple exploded in her mouth with a flavour she\\'d never experienced. It tasted of sunshine, laughter, and the comforting smell of rain on dry earth. She felt a surge of energy, of boundless possibility.\\n\\nFrom that day on, Flora\\'s life was anything but unremarkable. The backpack, it turned out, was magical. Whatever she needed, the backpack provided. Not necessarily what she *wanted*, but what she *needed*.\\n\\nOne day, facing a daunting math test, she reached in, hoping for a cheat sheet. Instead, she pulled out a skipping rope. Confused, she tucked it into her pocket. During the test, she felt a rising tide of anxiety. On impulse, she pulled out the rope and, ignoring the bewildered stares of her classmates, started skipping in the corner. The rhythm calmed her, cleared her head, and suddenly, the formulas clicked into place. She aced the test.\\n\\nAnother time, feeling lonely and ignored, she hoped for a new friend. The backpack gave her a packet of wildflower seeds. Disappointed, she almost tossed them aside. But then she remembered the empty patch of dirt behind the school. She planted the seeds, nurtured them, and soon, a riot of colours bloomed. Students, drawn to the vibrant flowers, started talking to her, helping her tend the garden. She found her community.\\n\\nThe backpack wasn\\'t always easy. Sometimes, it gave her things she didn\\'t understand or appreciate at first. A rusty key, a chipped teacup, a single, perfect feather. But each time, in its own strange way, the object taught her a lesson, filled a need she didn\\'t even know she had.\\n\\nOne day, rummaging through the backpack for a pen, Flora found something unexpected: a small, leather-bound book. Its pages were blank, but the title was embossed in gold: \"The Unwritten Story.\"\\n\\nShe understood. The backpack wasn\\'t just providing her with objects; it was providing her with opportunities, with the raw materials to build her own extraordinary life. It was up to her to write the story.\\n\\nFlora closed the book, a smile playing on her lips. She still had brown hair and brown eyes, and she still loved to read. But now, she carried herself with a newfound confidence, a spark of adventure in her eyes. She was no longer invisible. The magic backpack had helped her discover the magic within herself. And the greatest magic of all, she realised, was the power to create her own destiny, one chapter, one challenge, one adventure at a time.\\n')], role='model'), citation_metadata=None, finish_message=None, token_count=None, finish_reason=, avg_logprobs=-0.5562713704210647, grounding_metadata=None, index=None, logprobs_result=None, safety_ratings=None)], create_time=None, response_id=None, model_version='gemini-2.0-flash', prompt_feedback=None, usage_metadata=GenerateContentResponseUsageMetadata(cache_tokens_details=None, cached_content_token_count=None, candidates_token_count=752, candidates_tokens_details=[ModalityTokenCount(modality=, token_count=752)], prompt_token_count=8, prompt_tokens_details=[ModalityTokenCount(modality=, token_count=8)], thoughts_token_count=None, tool_use_prompt_token_count=None, tool_use_prompt_tokens_details=None, total_token_count=760), automatic_function_calling_history=[], parsed=None)" ] }, + "execution_count": 5, "metadata": {}, - "execution_count": 5 + "output_type": "execute_result" } ], "source": [ @@ -253,22 +244,18 @@ "cell_type": "code", "execution_count": 6, "metadata": { - "id": "c134fc5aaecc", - "colab": { - "base_uri": "https://localhost:8080/" - }, - "outputId": "f0280b94-36d0-4fdd-f81a-cbe3fc2029cc" + "id": "c134fc5aaecc" }, "outputs": [ { - "output_type": "execute_result", "data": { "text/plain": [ "GenerateContentResponse(candidates=[Candidate(content=Content(parts=[Part(video_metadata=None, thought=None, code_execution_result=None, executable_code=None, file_data=None, function_call=None, function_response=None, inline_data=None, text='Unzip endless possibilities with the Magic Backpack - more space, more adventure!\\n')], role='model'), citation_metadata=None, finish_message=None, token_count=None, finish_reason=, avg_logprobs=-0.6894590854644775, grounding_metadata=None, index=None, logprobs_result=None, safety_ratings=None)], create_time=None, response_id=None, model_version='gemini-2.0-flash', prompt_feedback=None, usage_metadata=GenerateContentResponseUsageMetadata(cache_tokens_details=None, cached_content_token_count=None, candidates_token_count=16, candidates_tokens_details=[ModalityTokenCount(modality=, token_count=16)], prompt_token_count=10, prompt_tokens_details=[ModalityTokenCount(modality=, token_count=10)], thoughts_token_count=None, tool_use_prompt_token_count=None, tool_use_prompt_tokens_details=None, total_token_count=26), automatic_function_calling_history=[], parsed=None)" ] }, + "execution_count": 6, "metadata": {}, - "execution_count": 6 + "output_type": "execute_result" } ], "source": [ @@ -310,33 +297,28 @@ "cell_type": "code", "execution_count": 7, "metadata": { - "id": "981415e25158", - "colab": { - "base_uri": "https://localhost:8080/", - "height": 53 - }, - "outputId": "f750d3c9-7a59-42b0-9021-5d10d29fc662" + "id": "981415e25158" }, "outputs": [ { - "output_type": "stream", "name": "stdout", + "output_type": "stream", "text": [ "Error: 503 Service Unavailable\n" ] }, { - "output_type": "execute_result", "data": { - "text/plain": [ - "'Unzip the impossible with the Magic Backpack - where adventure always fits!\\n'" - ], "application/vnd.google.colaboratory.intrinsic+json": { "type": "string" - } + }, + "text/plain": [ + "'Unzip the impossible with the Magic Backpack - where adventure always fits!\\n'" + ] }, + "execution_count": 7, "metadata": {}, - "execution_count": 7 + "output_type": "execute_result" } ], "source": [ @@ -379,8 +361,7 @@ "metadata": { "colab": { "name": "Error_handling.ipynb", - "toc_visible": true, - "provenance": [] + "toc_visible": true }, "kernelspec": { "display_name": "Python 3",