<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mridul Mishra on Medium]]></title>
        <description><![CDATA[Stories by Mridul Mishra on Medium]]></description>
        <link>https://medium.com/@mridulmishra8?source=rss-a60f2f7fbae2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Omwzws1mAz5TdrNq.jpg</url>
            <title>Stories by Mridul Mishra on Medium</title>
            <link>https://medium.com/@mridulmishra8?source=rss-a60f2f7fbae2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:16:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mridulmishra8/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build Real-World AI Applications with Google’s Gemini and Imagen Models (Includes Hack & Solution…]]></title>
            <link>https://medium.com/@mridulmishra8/building-real-world-ai-applications-with-googles-gemini-and-imagen-models-includes-hack-05d5a1d3cc2a?source=rss-a60f2f7fbae2------2</link>
            <guid isPermaLink="false">https://medium.com/p/05d5a1d3cc2a</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <dc:creator><![CDATA[Mridul Mishra]]></dc:creator>
            <pubDate>Tue, 13 May 2025 15:17:19 GMT</pubDate>
            <atom:updated>2025-05-13T20:40:34.671Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Real-World AI Applications with Google’s Gemini and Imagen Models (Includes Hack &amp; Solution to Finish Challenge Lab)</h3><p>In today’s fast-paced digital world, AI has become an integral part of numerous applications across various industries. From image recognition to natural language processing, AI models are transforming how we interact with technology. Recently, I completed the <a href="https://www.credly.com/badges/e3512828-bc11-4e49-83a4-de41e0f7f231/public_url"><strong>Google Skill Badge: Build Real-World AI Applications with Gemini and Imagen</strong></a>, and I’m excited to share my journey and insights with you.</p><h3>Introduction to Vertex AI, Gemini, and Imagen</h3><p>Vertex AI is Google’s unified platform for AI development, enabling developers to build, deploy, and scale AI models seamlessly. The platform provides access to powerful pre-trained models like Gemini and Imagen, which can be fine-tuned and integrated into applications without requiring extensive AI expertise.</p><ul><li><strong>Gemini</strong>: A versatile generative AI model capable of understanding and generating text, as well as processing images. It can be used for tasks like image recognition, text generation, and chat applications.</li><li><strong>Imagen</strong>: A specialized model for image generation. Given a text prompt, Imagen can create high-quality, realistic images, making it ideal for applications in design, marketing, and content creation.</li></ul><h3>The Workflow: How Everything Connects</h3><p>The magic of building AI applications with Gemini and Imagen on Vertex AI lies in how different tools, platforms, and APIs interact. Here’s a behind-the-scenes look at the workflow:</p><p><strong>1.</strong> <strong>Application Code :</strong></p><p>a) Code Development: You write Python code that utilizes the Vertex AI Python SDK to interact with Google’s AI services.</p><p>b) SDK Initialization: The code initializes the Vertex AI SDK with your project ID and region, establishing a connection to Google Cloud services.</p><pre>vertexai.init(project=&quot;your-project-id&quot;, location=&quot;your-region&quot;)</pre><p><strong>2.</strong> <strong>Connection to Vertex AI:</strong></p><p>a) Authentication: Using the provided credentials and project information, the SDK authenticates with Google Cloud.</p><p>b) Service Access: The SDK establishes a connection to Vertex AI services, granting access to pre-trained models like Gemini and Imagen.</p><p><strong>3. Model Loading:</strong></p><p>a) Model Selection: You specify which pre-trained model to use (Gemini for text and image understanding, Imagen for image generation).</p><p>b) Model Initialization: The SDK loads the specified model from Google’s model repository.</p><pre>model = ImageGenerationModel.from_pretrained(&quot;imagen-3.0-generate-002&quot;)</pre><p><strong>4. Input Processing:</strong></p><p>a) Input Preparation: Depending on the task, you prepare either text prompts or image files as input.</p><p>b) Request Formatting: The SDK formats the input into a structure that the AI model can process.</p><p><strong>5.</strong> <strong>Model Inference:</strong></p><p>a) Request Sending: The formatted request is sent to the specified AI model hosted on Vertex AI.</p><p>b) Model Processing:</p><p>i. Imagen: Generates images based on text prompts using its image generation capabilities.</p><p>ii. Gemini: Processes text or images and generates appropriate responses (text answers, chat responses).</p><pre>images = model.generate_images(<br>    prompt=prompt,<br>    number_of_images=1,<br>    seed=1,<br>    add_watermark=False,<br>)</pre><p><strong>6. Output Handling:</strong></p><p>a) Response Reception: The response from the AI model is received by the SDK.</p><p>b) Data Extraction: The SDK extracts the relevant data from the response (generated images, text answers).</p><p><strong>7. Local Processing:</strong></p><p>a) Image Saving: For image generation tasks, the generated images are saved locally.</p><p>b) Text Display: For text-based responses, the text is printed or returned for further use.</p><p><strong>8. Streaming (for Chat Applications):</strong></p><p>a) Stream Initialization: When using streaming, the chat session is initialized to receive responses incrementally.</p><p>b) Chunk Processing: As the model generates responses, they are sent in chunks and processed in real-time.</p><pre>for chunk in chat.send_message_stream(&quot;What are all the colors in a rainbow?&quot;):<br>    print(chunk.text, end=&quot;&quot;)</pre><p><strong>9. Integration and Application Logic:</strong></p><p>a) Function Development: You create functions that encapsulate the AI interactions (e.g., generate_bouquet_image, analyze_bouquet_image).</p><p>b) Application Flow: These functions are integrated into your main application logic to provide specific AI-powered features.</p><p><strong>10. Deployment and Scaling:</strong></p><p>a) Cloud Deployment: Once developed and tested, the application can be deployed on Google Cloud Platform for scalability and reliability.</p><p>b) API Integration: The application can be exposed as an API, allowing other systems to utilize the AI capabilities.</p><figure><img alt="Diagram titled “Building AI Applications with Google’s Gemini and Imagen Models,” showing a central node connected to surrounding nodes representing steps like Application Code, Input Processing, Model Inference, Integration and Application Logic, Local Processing, Streaming, Connection to Vertex AI, Model Loading, and Output Handling. Each step lists related sub-processes." src="https://cdn-images-1.medium.com/max/794/1*UMe5bulwbA7Lv_vjJMxq_w.png" /></figure><h3>Lab 1: AI Image Recognition with Gemini</h3><p>The first lab focused on building an AI Image Recognition application using the Gemini model on Vertex AI. The objective was to connect to Vertex AI, load the pre-trained Gemini model, and send image + text questions to the model. The model would then process the input and provide text-based answers.</p><p>Here’s a code snippet demonstrating how to use the Gemini model for image recognition:</p><pre>from google import genai<br>from google.genai.types import HttpOptions, Part<br><br>client = genai.Client(http_options=HttpOptions(api_version=&quot;v1&quot;))<br>response = client.models.generate_content(<br>    model=&quot;gemini-2.0-flash-001&quot;,<br>    contents=[<br>        &quot;What is shown in this image?&quot;,<br>        Part.from_uri(<br>            file_uri=&quot;gs://cloud-samples-data/generative-ai/image/scones.jpg&quot;,<br>            mime_type=&quot;image/jpeg&quot;,<br>        ),<br>    ],<br>)<br>print(response.text)</pre><p>In this code, we initialize the Gemini client, specify the model, and send a question along with an image URI. The model processes the image and returns a text description of what it sees</p><h3>Lab 2: AI Image Generation with Imagen</h3><p>The second lab was all about generating images using the Imagen model on Vertex AI. The task involved connecting to Vertex AI, loading the pre-trained Imagen model, and sending text prompts to generate images.</p><p>Here’s an example of generating an image with Imagen:</p><pre>import vertexai<br>from vertexai.preview.vision_models import ImageGenerationModel<br><br>def generate_image(project_id, location, output_file, prompt):<br>    vertexai.init(project=project_id, location=location)<br>    model = ImageGenerationModel.from_pretrained(&quot;imagen-3.0-generate-002&quot;)<br>    images = model.generate_images(<br>        prompt=prompt,<br>        number_of_images=1,<br>        seed=1,<br>        add_watermark=False,<br>    )<br>    images[0].save(location=output_file)<br>    return images<br><br>generate_image(<br>    project_id=&quot;your-project-id&quot;,<br>    location=&quot;your-region&quot;,<br>    output_file=&#39;image.jpeg&#39;,<br>    prompt=&#39;Create an image of a cricket ground in the heart of Los Angeles&#39;,<br>)</pre><p>This code initializes Vertex AI, loads the Imagen model, and generates an image based on the provided text prompt. The generated image is then saved locally.</p><h3>Lab 3: Chat Applications with Gemini</h3><p>The third lab explored building chat applications using the Gemini model. It covered sending text prompts to the model and extracting chat responses, both with and without streaming.</p><p><strong>Without Streaming:</strong></p><pre>from google import genai<br>from google.genai.types import HttpOptions, ModelContent, Part, UserContent<br><br>client = genai.Client(<br>    vertexai=True,<br>    project=&quot;your-project-id&quot;,<br>    location=&quot;your-region&quot;,<br>    http_options=HttpOptions(api_version=&quot;v1&quot;)<br>)<br>chat = client.chats.create(<br>    model=&quot;gemini-2.0-flash-001&quot;,<br>    history=[<br>        UserContent(parts=[Part(text=&quot;Hello&quot;)]),<br>        ModelContent(<br>            parts=[Part(text=&quot;Great to meet you. What would you like to know?&quot;)],<br>        ),<br>    ],<br>)<br>response = chat.send_message(&quot;What are all the colors in a rainbow?&quot;)<br>print(response.text)</pre><p>With Streaming:</p><pre>from google import genai<br>from google.genai.types import HttpOptions<br><br>client = genai.Client(<br>    vertexai=True,<br>    project=&quot;your-project-id&quot;,<br>    location=&quot;your-region&quot;,<br>    http_options=HttpOptions(api_version=&quot;v1&quot;)<br>)<br>chat = client.chats.create(model=&quot;gemini-2.0-flash-001&quot;)<br>response_text = &quot;&quot;<br><br>for chunk in chat.send_message_stream(&quot;What are all the colors in a rainbow?&quot;):<br>    print(chunk.text, end=&quot;&quot;)<br>    response_text += chunk.text</pre><p>Streaming allows you to receive responses as they are generated, providing a more interactive experience.</p><h3>Challenge Lab: GenAI Application</h3><p>The challenge lab simulated a real-world scenario where I had to develop functions for generating bouquet images and analyzing them.</p><p><strong>Task 1: Generate Bouquet Image:</strong></p><pre>import argparse<br>import os<br>import vertexai<br>from vertexai.preview.vision_models import ImageGenerationModel<br><br>def generate_bouquet_image(prompt):<br>    # Initialize Vertex AI<br>    vertexai.init(project=&quot;your-project-id&quot;, location=&quot;your-region&quot;)<br>    <br>    # Create the image generation model<br>    image_model = ImageGenerationModel.from_pretrained(&quot;imagen-3.0-generate-002&quot;)<br>    <br>    # Generate the image<br>    response = image_model.generate_images(<br>        prompt=prompt,<br>    )<br>    <br>    # Save the generated image<br>    image_path = &quot;generated_bouquet.png&quot;<br>    <br>    # The first generated image<br>    generated_image = response.images[0]<br>    <br>    # Save image to disk<br>    with open(image_path, &quot;wb&quot;) as f:<br>        f.write(generated_image._image_bytes)<br>    <br>    print(f&quot;Image generated and saved to {image_path}&quot;)<br>    return image_path<br><br>if __name__ == &quot;__main__&quot;:<br>    prompt = &quot;Create an image containing a bouquet of 2 sunflowers and 3 roses&quot;<br>    image_path = generate_bouquet_image(prompt)</pre><p>Output of this Task is the image :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6JCNZJyygy6IlDIHi-EIA.jpeg" /></figure><p><strong>Task 2: Analyze Bouquet Image:</strong></p><pre>import os<br>import vertexai<br>from vertexai.generative_models import GenerativeModel, Part<br><br>def analyze_bouquet_image(image_path):<br>    # Initialize Vertex AI<br>    vertexai.init(project=&quot;&quot;, location=&quot;us-central1&quot;)<br>    <br>    # Create a connection to the Gemini model<br>    model = GenerativeModel(&quot;gemini-2.0-flash-001&quot;)<br>    <br>    # Read the image file<br>    with open(image_path, &quot;rb&quot;) as f:<br>        image_data = f.read()<br>    <br>    # Create image Part object<br>    image_part = Part.from_data(image_data, mime_type=&quot;image/png&quot;)<br>    <br>    # Create the prompt for birthday wishes based on the image<br>    prompt = &quot;Generate beautiful birthday wishes based on this bouquet image.&quot;<br>    <br>    # Generate content with streaming enabled<br>    responses = model.generate_content(<br>        [prompt, image_part],<br>        stream=True<br>    )<br>    <br>    # Process the streaming response<br>    full_response = &quot;&quot;<br>    print(&quot;Generating birthday wishes based on the bouquet image:&quot;)<br>    for response in responses:<br>        text_chunk = response.text<br>        print(text_chunk, end=&quot;&quot;, flush=True)<br>        full_response += text_chunk<br>    <br>    print(&quot;\n\nAnalysis complete!&quot;)<br>    return full_response<br><br>if __name__ == &quot;__main__&quot;:<br>    image_path = &quot;generated_bouquet.png&quot;  # Use the image path from Task 1<br>    birthday_wishes = analyze_bouquet_image(image_path)<br><br></pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*QrVl5-uVGkzNZFygirj3sA.png" /></figure><h3>Workaround Hack for Qwiklab Issues:</h3><p>During the lab, I encountered issues with the lab evaluation task 2 below as shown in the screenshots below( and many people I contacted had issues too) not recognizing the generated image. To circumvent this, I used a publicly accessible image from Google Cloud Storage. This hack allowed me to complete the lab successfully.</p><figure><img alt="A screenshot showing issues in task 2 of challenge Lab" src="https://cdn-images-1.medium.com/max/733/1*WfmhuoFaZ0ObAr5UP0LI2w.png" /><figcaption>Issues in task 2</figcaption></figure><figure><img alt="A screenshot showing issues in task 2 of challenge Lab" src="https://cdn-images-1.medium.com/max/726/1*jyIg2hNXbtm7SRWPPG5WLA.png" /><figcaption>Issues in Task 2</figcaption></figure><p>Run the following command in terminal to see the public images available in google bucket “generativeai-downloads”. You will get a list of many images, copy path of any image and use it as shown in code snippet below:</p><pre> gsutil ls gs://generativeai-downloads/images/</pre><pre>import vertexai<br>from vertexai.generative_models import GenerativeModel, Part<br><br>def generate_text(project_id: str, location: str) -&gt; str:<br>  # Initialize Vertex AI<br>  vertexai.init(project=project_id, location=location)<br>  # Load the model<br>  multimodal_model = GenerativeModel(&quot;gemini-2.0-flash-001&quot;)<br>  # Query the model<br>  response = multimodal_model.generate_content(<br>    [<br>      # Add an example image<br>      Part.from_uri(<br>        &quot;gs://generativeai-downloads/images/piano.jpeg&quot;, mime_type=&quot;image/jpeg&quot;<br>      ),<br>      # Add an example query<br>      &quot;what is shown in this image?&quot;,<br>    ]<br>  )<br><br>  return response.text<br><br>project_id = &quot;your-project-id&quot;<br>location = &quot;region&quot;<br><br>response = generate_text(project_id, location)<br>print(response)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*JKiqfPLCVq0qtwPGbiGkNw.png" /></figure><h3>Explanation of the Hack:</h3><ul><li><strong>Publicly Accessible Image</strong>: The image used is stored in a public Google Cloud Storage bucket, so it doesn’t require authentication to access.</li><li><strong>Correct Model Usage</strong>: The Gemini model is correctly initialised and used to generate content based on the image and prompt.</li><li><strong>Qwiklab Environment</strong>: The project ID and location are specific to the Qwiklab environment, ensuring the code runs within the lab’s allocated resources.</li></ul><p>This workaround allowed me to complete the lab successfully despite the evaluation issues.</p><h3>Disclaimer:</h3><p><strong>I want to emphasize that sometimes the correct code works perfectly, and the hack isn’t needed. However, in some cases, due to environment-specific issues or other unforeseen circumstances, the hack became necessary for me to proceed. I am not encouraging anyone to use this hack as a standard practice. In fact, after further refining my code and understanding the lab environment better, I was able to complete the lab using the correct code without any issues. This hack was merely a temporary solution to overcome a roadblock during my initial attempts and is shared here solely for informational purposes and to illustrate potential troubleshooting approaches.</strong></p><h3>Conclusion</h3><p>Completing this skill badge has provided me with valuable hands-on experience in building AI applications using Google’s Gemini and Imagen models on Vertex AI. From image recognition to text generation and chat applications, I’ve explored various capabilities of these powerful models. The knowledge gained will undoubtedly be useful in future AI projects and in creating innovative solutions for real-world problems.</p><p>Understanding the workflow of how different components interact — from your application code through the Vertex AI SDK to Google’s pre-trained models — provides a clearer picture of the AI application development process. This behind-the-scenes look helps in optimising applications, troubleshooting issues, and designing more efficient AI-powered solutions.</p><p>If you’re interested in exploring AI applications further, I highly recommend checking out <a href="https://cloud.google.com/vertex-ai?hl=en">Google’s Vertex AI platform</a> and experimenting with the Gemini and Imagen models. The potential for creativity and problem-solving with these tools is immense. Happy Learning!</p><p>#AI #MachineLearning #DeepLearning #GoogleAI #VertexAI #GenerativeAI #GeminiModel #ImagenModel #Python #APIDevelopment #CloudComputing #TechTutorials #AIDevelopment #Qwiklabs #TechBlogging</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05d5a1d3cc2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Prompts to Power: My Journey in Developing GenAI Apps with Gemini and Streamlit]]></title>
            <link>https://medium.com/@mridulmishra8/from-prompts-to-power-my-journey-in-developing-genai-apps-with-gemini-and-streamlit-f283bbd06865?source=rss-a60f2f7fbae2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f283bbd06865</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[gemini-api]]></category>
            <category><![CDATA[streamlit-app-deployment]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Mridul Mishra]]></dc:creator>
            <pubDate>Wed, 07 May 2025 12:31:06 GMT</pubDate>
            <atom:updated>2025-05-07T15:34:54.973Z</atom:updated>
            <content:encoded><![CDATA[<p>Generative AI’s capabilities are unleashed by the power of well-crafted <strong>prompts</strong>. Like a skilled marksman, a precise prompt structure can hit the mark, yielding remarkable results and unlocking new possibilities that propel innovation forward. They are the foundation upon which we build our interactions with large language models (LLMs), guiding them to produce content that aligns with our vision. In this article, I’ll take you through my journey in the “Develop GenAI Apps with Gemini and Streamlit” course, where I learned to harness the power of generative AI to create innovative applications.</p><h3>The Foundation: Understanding Prompts and Their Power</h3><p><a href="https://medium.com/@mridulmishra8/crafting-effective-prompts-a-journey-through-prompt-design-in-vertex-ai-d3c8a9995991">Prompts</a> are more than just questions or commands — they are carefully crafted inputs designed to elicit specific responses from AI models. They serve as guides, enhancing relevance, improving quality, and allowing for customization of the output. A well-structured prompt includes a task definition, context, examples, parameters, and constraints.</p><h3>Key Learnings from the Course</h3><p>The aim of the course is to use Gemini(LLM model) using streamlit(web-app from AI code) and Python SDK as shown in figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*eugchT3wIB6G17ngupgdqQ.png" /><figcaption>Using LLMs with streamlit and Python SDK</figcaption></figure><h3>Lab 1: Getting Started with the Gemini API in Vertex AI</h3><p>This lab introduced me to the fundamentals of interacting with the Gemini API. I learned how to set up my environment, authenticate with Google Cloud, and generate text from simple text prompts. The lab emphasized the importance of prompt structure and how different parameters like temperature and token limits can significantly impact the output.</p><figure><img alt="Python code snippet showing project ID and location variables, and importing the ‘os’ library" src="https://cdn-images-1.medium.com/max/786/1*xrBpDhZHVZJmpFy3IVVg8g.png" /><figcaption>Setting Up the Environment Variable</figcaption></figure><figure><img alt="Python code snippet setting model ID, API host, and API endpoint environment variable, likely for configuring an API call" src="https://cdn-images-1.medium.com/max/965/1*m4nIeKGfvMTAs_QRcWF8fw.png" /><figcaption>Setting Up the Gemini Model</figcaption></figure><figure><img alt="Command to download an image from Google Cloud storage" src="https://cdn-images-1.medium.com/max/1024/1*tG4WK06UfT7anjOMxznseg.png" /><figcaption>Downloading Image from Google cloud storage</figcaption></figure><p>Code snippet for multimodal input :</p><pre>image_file=&quot;image.jpg&quot;<br>if [[ -f &quot;$image_file&quot; ]]; then<br>  if command -v base64 &amp;&gt; /dev/null; then<br>    # base64 is available<br>    if [[ &quot;$(uname -s)&quot; == &quot;Darwin&quot; ]]; then<br>      # macOS -b 0 to avoid line wrapping<br>      data=$(base64 -b 0 -i &quot;$image_file&quot;)<br>    else<br>      # Linux -w 0 to avoid line wrapping<br>      data=$(base64 -w 0 &quot;$image_file&quot;)<br>    fi<br>  else<br>    echo &quot;Error: base64 command not found.&quot;<br>    exit 1<br>  fi<br>else<br>  echo &quot;Error: Image file &#39;$image_file&#39; not found.&quot;<br>  exit 1<br>fi<br><br>curl -X POST I am running a few minutes late; my previous meeting is running over.<br>  -H &quot;Authorization: Bearer $(gcloud auth print-access-token)&quot; I am running a few minutes late; my previous meeting is running over.<br>  -H &quot;Content-Type: application/json&quot; I am running a few minutes late; my previous meeting is running over.<br>  https://${API_ENDPOINT}:generateContent I am running a few minutes late; my previous meeting is running over.<br>  -d &quot;{<br>      &#39;contents&#39;: {<br>        &#39;role&#39;: &#39;USER&#39;,<br>        &#39;parts&#39;: [<br>          {<br>            &#39;text&#39;: &#39;Is it a cat?&#39;<br>          },<br>          {<br>            &#39;inline_data&#39;: {<br>              &#39;data&#39;: &#39;${data}&#39;,<br>              &#39;mime_type&#39;:&#39;image/jpeg&#39;<br>            }<br>          }<br>        ]<br>       }<br>    }&quot; 2&gt;/dev/null &gt;response.json<br><br>jq -r &quot;.candidates[].content.parts[].text&quot; response.json</pre><h3>Lab 2: Building a Streamlit Application</h3><p>In this lab, I explored the Streamlit framework to create a user interface for my GenAI application. I integrated the Gemini API with Streamlit, allowing users to input their preferences and generate meal recommendations. This lab highlighted the importance of creating an intuitive UI to enhance user experience.</p><p><a href="https://streamlit.io/">Streamlit</a> is a game-changer for building interactive data applications. This open-source Python framework lets us create user-friendly apps with minimal effort, no extensive web development skills required. With Streamlit, you define the app’s layout, visualizations, and interactivity using Python functions and decorators, and the framework handles the front-end rendering.</p><p>Streamlit shines with rapid prototyping, real-time updates, and seamless integration with popular Python libraries like Pandas, Matplotlib, and Plotly. Its reactive apps make it perfect for dashboards, machine learning demos, or data exploration tools. Deployment is a breeze with options like Streamlit Cloud or Docker, making it easy to share your apps with a broader audience.</p><figure><img alt="Python code snippet importing os and google.generativeai, setting project ID and location from environment variables or default, and initializing a genai client" src="https://cdn-images-1.medium.com/max/1024/1*DWidTwpYg3H_rfjvuh8S7w.png" /><figcaption>Setting up the Gemini client</figcaption></figure><p>Using Function Calling in a chat session to answer user’s questions about the Google Store:</p><pre>get_product_info = FunctionDeclaration(<br>    name=&quot;get_product_info&quot;,<br>    description=&quot;Get the stock amount and identifier for a given product&quot;,<br>    parameters={<br>        &quot;type&quot;: &quot;OBJECT&quot;,<br>        &quot;properties&quot;: {<br>            &quot;product_name&quot;: {&quot;type&quot;: &quot;STRING&quot;, &quot;description&quot;: &quot;Product name&quot;}<br>        },<br>    },<br>)</pre><pre>get_store_location = FunctionDeclaration(<br>    name=&quot;get_store_location&quot;,<br>    description=&quot;Get the location of the closest store&quot;,<br>    parameters={<br>        &quot;type&quot;: &quot;OBJECT&quot;,<br>        &quot;properties&quot;: {&quot;location&quot;: {&quot;type&quot;: &quot;STRING&quot;, &quot;description&quot;: &quot;Location&quot;}},<br>    },<br>)</pre><pre>place_order = FunctionDeclaration(<br>    name=&quot;place_order&quot;,<br>    description=&quot;Place an order&quot;,<br>    parameters={<br>        &quot;type&quot;: &quot;OBJECT&quot;,<br>        &quot;properties&quot;: {<br>            &quot;product&quot;: {&quot;type&quot;: &quot;STRING&quot;, &quot;description&quot;: &quot;Product name&quot;},<br>            &quot;address&quot;: {&quot;type&quot;: &quot;STRING&quot;, &quot;description&quot;: &quot;Shipping address&quot;},<br>        },<br>    },<br>)</pre><pre>retail_tool = Tool(<br>    function_declarations=[<br>        get_product_info,<br>        get_store_location,<br>        place_order,<br>    ],<br>)<br>`</pre><p>Using function calling to geocode addresses with a maps API:</p><pre>def get_location(<br>    amenity: str | None = None,<br>    street: str | None = None,<br>    city: str | None = None,<br>    county: str | None = None,<br>    state: str | None = None,<br>    country: str | None = None,<br>    postalcode: str | None = None,<br>) -&gt; list[dict]:<br>    &quot;&quot;&quot;<br>    Get latitude and longitude for a given location.</pre><pre>    Args:<br>        amenity (str | None): Amenity or Point of interest.<br>        street (str | None): Street name.<br>        city (str | None): City name.<br>        county (str | None): County name.<br>        state (str | None): State name.<br>        country (str | None): Country name.<br>        postalcode (str | None): Postal code.</pre><pre>    Returns:<br>        list[dict]: A list of dictionaries with the latitude and longitude of the given location.<br>                    Returns an empty list if the location cannot be determined.<br>    &quot;&quot;&quot;<br>    base_url = &quot;https://nominatim.openstreetmap.org/search&quot;<br>    params = {<br>        &quot;amenity&quot;: amenity,<br>        &quot;street&quot;: street,<br>        &quot;city&quot;: city,<br>        &quot;county&quot;: county,<br>        &quot;state&quot;: state,<br>        &quot;country&quot;: country,<br>        &quot;postalcode&quot;: postalcode,<br>        &quot;format&quot;: &quot;json&quot;,<br>    }<br>    # Filter out None values from parameters<br>    params = {k: v for k, v in params.items() if v is not None}</pre><pre>    try:<br>        response = requests.get(base_url, params=params, headers={&quot;User-Agent&quot;: &quot;none&quot;})<br>        response.raise_for_status()<br>        return response.json()<br>    except requests.RequestException as e:<br>        print(f&quot;Error fetching location data: {e}&quot;)<br>        return []</pre><pre>prompt = &quot;&quot;&quot;<br>I want to get the coordinates for the following address:<br>1600 Amphitheatre Pkwy, Mountain View, CA 94043<br>&quot;&quot;&quot;</pre><pre>response = client.models.generate_content(<br>    model=MODEL_ID,<br>    contents=prompt,<br>    config=GenerateContentConfig(tools=[get_location], temperature=0),<br>)<br>print(response.text)</pre><h3>Lab 3: Testing and Refining the Application</h3><p>Testing is a crucial step in the development process. I ran my application locally in Cloud Shell, ensuring it functioned as expected and making adjustments based on the results. This lab taught me the importance of rigorous testing before deployment.</p><figure><img alt="Python code snippet importing os and vertexai, setting project ID and location from environment variables or default, and initializing vertexai." src="https://cdn-images-1.medium.com/max/1024/1*m7yxQL4mAtZIMOFLr4BDGA.png" /><figcaption>Setting up the project and initializing the Vertex AI SDK</figcaption></figure><p>Setting up and interacting with a Gemini model:</p><pre>from vertexai.generative_models import (<br>    GenerationConfig,<br>    GenerativeModel,<br>    HarmBlockThreshold,<br>    HarmCategory,<br>    Image,<br>    Part,<br>    SafetySetting,<br>)</pre><pre>model = GenerativeModel(&quot;gemini-2.0-flash&quot;)</pre><pre>generation_config = GenerationConfig(<br>    temperature=0.9,<br>    top_p=1.0,<br>    top_k=32,<br>    candidate_count=1,<br>    max_output_tokens=8192,<br>)<br>responses = model.generate_content(&quot;Why is the sky blue?&quot;, stream=True)</pre><pre>for response in responses:<br>    print(response.text, end=&quot;&quot;)</pre><p>Setting up a Gemini Chat Client:</p><pre>chat = model.start_chat()</pre><pre>prompt = &quot;&quot;&quot;My name is Ned. You are my personal assistant. My favorite movies are Lord of the Rings and Hobbit.</pre><pre>Suggest another movie I might like.<br>&quot;&quot;&quot;</pre><pre>response = chat.send_message(prompt)</pre><pre>print(response.text)</pre><pre>prompt = &quot;Are my favorite movies based on a book series?&quot;</pre><pre>responses = chat.send_message(prompt)</pre><pre>print(response.text)</pre><h3>Lab 4: Deploying to Cloud Run</h3><p>With my application thoroughly tested, I prepared it for deployment by creating a Dockerfile and pushing the Docker image to Google’s Artifact Registry. I then deployed the application to Cloud Run, making it accessible via a URL. This lab provided hands-on experience with containerization and cloud deployment.</p><p><strong>Unlock Seamless Deployment with Docker: </strong>Dockers, or Docker containers, are lightweight, portable units that package an application along with its dependencies, libraries, and configuration files into a single, standardized environment. Built on containerization technology, Docker allows developers to create, deploy, and run applications consistently across different systems, regardless of the underlying operating system or hardware. By isolating applications in containers, Docker ensures that software runs reliably in development, testing, and production environments. Unlike traditional virtual machines, Docker containers share the host system’s kernel, making them highly efficient in terms of resource usage and startup speed, revolutionizing modern software development and deployment practices.</p><p><strong>Streamlining Gemini AI App Deployment: </strong>Docker simplifies Gemini AI deployment by providing a consistent environment for complex machine learning models and dependencies. With Docker, developers can package Gemini AI components into containers, ensuring identical behavior across environments. This eliminates version mismatches and bugs, enabling rapid scaling, easy updates, and enhanced security. Docker is the perfect choice for deploying sophisticated AI applications like Gemini AI.</p><p>Tasks done in the lab:</p><p>Clone the repository with docker image:</p><pre>git clone https://github.com/GoogleCloudPlatform/generative-ai.git --depth=1</pre><p>Setup the Python virtual environment and install the dependencies:</p><pre>python3 -m venv gemini-streamlit<br>source gemini-streamlit/bin/activate<br>pip install -r requirements.txt</pre><pre>AR_REPO=&#39;gemini-repo&#39;<br>SERVICE_NAME=&#39;gemini-streamlit-app&#39; <br>gcloud artifacts repositories create &quot;$AR_REPO&quot; --location=&quot;$GOOGLE_CLOUD_REGION&quot; --repository-format=Docker<br>gcloud builds submit --tag &quot;$GOOGLE_CLOUD_REGION-docker.pkg.dev/$GOOGLE_CLOUD_PROJECT/$AR_REPO/$SERVICE_NAME&quot;</pre><p>The final step is to deploy the service in Cloud Run with the image that we had built :</p><pre>gcloud run deploy &quot;$SERVICE_NAME&quot; I am running a few minutes late; my previous meeting is running over.<br>  --port=8080 I am running a few minutes late; my previous meeting is running over.<br>  --image=&quot;$GOOGLE_CLOUD_REGION-docker.pkg.dev/$GOOGLE_CLOUD_PROJECT/$AR_REPO/$SERVICE_NAME&quot; I am running a few minutes late; my previous meeting is running over.<br>  --allow-unauthenticated I am ruI am running a few minutes late; my previous meeting is running over.nning a few minutes late; my previous meeting is running over.<br>  --region=$GOOGLE_CLOUD_REGION I am running a few minutes late; my previous meeting is running over.<br>  --platform=managed  I am running a few minutes late; my previous meeting is running over.<br>  --project=$GOOGLE_CLOUD_PROJECT I am running a few minutes late; my previous meeting is running over.<br>  --set-env-vars=GOOGLE_CLOUD_PROJECT=$GOOGLE_CLOUD_PROJECT,GOOGLE_CLOUD_REGION=$GOOGLE_CLOUD_REGION</pre><figure><img alt="Screenshot of the Gemini API in Vertex AI user interface. The Freeform playground is selected. Options are available to choose a model (Gemini 2.0 Flash selected), and adjust temperature, maximum number of tokens, and Top P using sliders. A text box contains the prompt “Explain use of Streamlit”. There is also a button labeled “Open in Cloud Run”." src="https://cdn-images-1.medium.com/max/905/1*SckFAsbHbyHy9wzLi1XRIw.png" /><figcaption>Docker File Generated via Streamlit</figcaption></figure><p>Story Generation Using Gemini Vertex AI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XU06B292FdfFqIvG0u8uCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-QANA9QCE8WtykWmE3nyQ.png" /><figcaption>Story Generation through Gemini API docker</figcaption></figure><h3>Lab 5: Challenge Lab</h3><p>The Challenge Lab of the “Develop GenAI Apps with Gemini and Streamlit” course put my skills to the test by simulating a real-world scenario. Here’s a detailed breakdown of the tasks and my journey through them:</p><p><strong>Task 1- Use cURL to Test a Prompt with the API:</strong>I worked on a cURL command to send a prompt to the Gemini API, ensuring that the request included necessary headers and the JSON payload with the prompt.</p><p><strong>Task 2-Write Streamlit Framework and Prompt Python Code: I added </strong>a radio button for wine preference and crafted a dynamic prompt that incorporated all user inputs.</p><p>The code of chef.py after incorporating Task 2 :</p><pre>import os<br>import streamlit as st<br>import logging<br>from google.cloud import logging as cloud_logging<br>import vertexai<br>from vertexai.preview.generative_models import (<br>    GenerationConfig,<br>    GenerativeModel,<br>    HarmBlockThreshold,<br>    HarmCategory,<br>    Part,<br>)<br>from datetime import (<br>    date,<br>    timedelta,<br>)<br># configure logging<br>logging.basicConfig(level=logging.INFO)<br># attach a Cloud Logging handler to the root logger<br>log_client = cloud_logging.Client()<br>log_client.setup_logging()<br><br>PROJECT_ID = os.environ.get(&quot;GCP_PROJECT&quot;)  # Your Google Cloud Project ID<br>LOCATION = os.environ.get(&quot;GCP_REGION&quot;)  # Your Google Cloud Project Region<br>vertexai.init(project=PROJECT_ID, location=LOCATION)<br><br><br>@st.cache_resource<br>def load_models():<br>    text_model_flash = GenerativeModel(&quot;gemini-2.0-flash-001&quot;)<br>    return text_model_flash<br><br><br>def get_gemini_flash_text_response(<br>    model: GenerativeModel,<br>    contents: str,<br>    generation_config: GenerationConfig,<br>    stream: bool = True,<br>):<br>    safety_settings = {<br>        HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,<br>        HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,<br>        HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,<br>        HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,<br>    }<br><br>    responses = model.generate_content(<br>        prompt,<br>        generation_config=generation_config,<br>        safety_settings=safety_settings,<br>        stream=stream,<br>    )<br><br>    final_response = []<br>    for response in responses:<br>        try:<br>            # st.write(response.text)<br>            final_response.append(response.text)<br>        except IndexError:<br>            # st.write(response)<br>            final_response.append(&quot;&quot;)<br>            continue<br>    return &quot; &quot;.join(final_response)<br><br>st.header(&quot;Vertex AI Gemini API&quot;, divider=&quot;gray&quot;)<br>text_model_flash = load_models()<br><br>st.write(&quot;Using Gemini Flash - Text only model&quot;)<br>st.subheader(&quot;AI Chef&quot;)<br><br>cuisine = st.selectbox(<br>    &quot;What cuisine do you desire?&quot;,<br>    (&quot;American&quot;, &quot;Chinese&quot;, &quot;French&quot;, &quot;Indian&quot;, &quot;Italian&quot;, &quot;Japanese&quot;, &quot;Mexican&quot;, &quot;Turkish&quot;),<br>    index=None,<br>    placeholder=&quot;Select your desired cuisine.&quot;<br>)<br><br>dietary_preference = st.selectbox(<br>    &quot;Do you have any dietary preferences?&quot;,<br>    (&quot;Diabetese&quot;, &quot;Glueten free&quot;, &quot;Halal&quot;, &quot;Keto&quot;, &quot;Kosher&quot;, &quot;Lactose Intolerance&quot;, &quot;Paleo&quot;, &quot;Vegan&quot;, &quot;Vegetarian&quot;, &quot;None&quot;),<br>    index=None,<br>    placeholder=&quot;Select your desired dietary preference.&quot;<br>)<br><br>allergy = st.text_input(<br>    &quot;Enter your food allergy:  \n\n&quot;, key=&quot;allergy&quot;, value=&quot;peanuts&quot;<br>)<br><br>ingredient_1 = st.text_input(<br>    &quot;Enter your first ingredient:  \n\n&quot;, key=&quot;ingredient_1&quot;, value=&quot;ahi tuna&quot;<br>)<br><br>ingredient_2 = st.text_input(<br>    &quot;Enter your second ingredient:  \n\n&quot;, key=&quot;ingredient_2&quot;, value=&quot;chicken breast&quot;<br>)<br><br>ingredient_3 = st.text_input(<br>    &quot;Enter your third ingredient:  \n\n&quot;, key=&quot;ingredient_3&quot;, value=&quot;tofu&quot;<br>)<br><br><br># Task 2.5<br># Complete Streamlit framework code for the user interface, add the wine preference radio button to the interface.<br># https://docs.streamlit.io/library/api-reference/widgets/st.radio<br><br># Add Streamlit framework radio button option for the wine variable. Include options for Red, White and None<br>wine = st.radio(<br>    &quot;Do you have any wine preference?&quot;,<br>    (&quot;Red&quot;, &quot;White&quot;, &quot;None&quot;),<br>    index=None,<br>    horizontal=True,<br>)<br><br><br>max_output_tokens = 2048<br><br># Task 2.6<br># Modify this prompt with the custom chef prompt.<br>prompt = f&quot;&quot;&quot;I am a Chef.  I need to create {cuisine} \n<br>recipes for customers who want {dietary_preference} meals. \n<br>However, don&#39;t include recipes that use ingredients with the customer&#39;s {allergy} allergy. \n<br>I have {ingredient_1}, \n{ingredient_2}, \n<br>and {ingredient_3} \n<br>in my kitchen and other ingredients. \n<br>The customer&#39;s wine preference is {wine} \n<br>Please provide some for meal recommendations.<br>For each recommendation include preparation instructions,<br>time to prepare<br>and the recipe title at the beginning of the response.<br>Then include the wine paring for each recommendation.<br>At the end of the recommendation provide the calories associated with the meal<br>and the nutritional facts.<br>&quot;&quot;&quot;<br><br>config = {<br>    &quot;temperature&quot;: 0.8,<br>    &quot;max_output_tokens&quot;: 2048,<br>}<br><br>generate_t2t = st.button(&quot;Generate my recipes.&quot;, key=&quot;generate_t2t&quot;)<br>if generate_t2t and prompt:<br>    # st.write(prompt)<br>    with st.spinner(&quot;Generating your recipes using Gemini...&quot;):<br>        first_tab1, first_tab2 = st.tabs([&quot;Recipes&quot;, &quot;Prompt&quot;])<br>        with first_tab1:<br>            response = get_gemini_flash_text_response(<br>                text_model_flash,<br>                prompt,<br>                generation_config=config,<br>            )<br>            if response:<br>                st.write(&quot;Your recipes:&quot;)<br>                st.write(response)<br>                logging.info(response)<br>        with first_tab2:<br>            st.text(prompt)<br><br></pre><p>Remember to upload the updated chef.py to <strong>set at lab start-generative-ai</strong> bucket by running below command:</p><pre>gcloud storage cp &lt;your-file.py&gt; &lt;google-storage-destination&gt;</pre><p><strong>Task 3- Test the Application: </strong>I set up a Python virtual environment, installed dependencies, and ran the Streamlit application locally(follow the sequence).</p><pre>python3 -m venv gemini-streamlit<br>source gemini-streamlit/bin/activate<br>pip install -r requirements.txt<br><br>export GCP_PROJECT=&#39;your-project-id&#39;<br>export GCP_REGION=&#39;your-region&#39;<br><br>streamlit run chef.py \<br>  --browser.serverAddress=localhost \<br>  --server.enableCORS=false \<br>  --server.enableXsrfProtection=false \<br>  --server.port 8080</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*9rU2xojr_vG9jmHYuQ-k1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*qXPFxgSnuQEApoDxVy_ztA.png" /><figcaption>Streamlit enabled Web Interface for Gemini API to generate recipes</figcaption></figure><p><strong>Task 4-Modify the Dockerfile and Push Image to the Artifact Registry: </strong>I modified a Dockerfile that defined the application’s environment and dependencies. I then built the Docker image and pushed it to the Artifact Registry.</p><p>First verify the environment variables again and define AR_repo and service_name.</p><pre>export REGION=&#39;your-region&#39;<br>export PROJECT=&#39;your-project-id&#39;<br>export AR_REPO=&#39;gemini-repo&#39;<br>export SERVICE_NAME=&#39;chef-streamlit-app&#39;</pre><p>Submit command to push the Docker image to the Artifact Registry:</p><pre>gcloud builds submit --tag &quot;$REGION-docker.pkg.dev/$PROJECT/$AR_REPO/$SERVICE_NAME&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ub_Rqkhx9vr-N992Ex2XAw.png" /><figcaption>Modifying the Dockerfile and pushing image to the Artifact Registry</figcaption></figure><figure><img alt="The image shows the successful build and push of a Docker container for a Streamlit application to Google Cloud’s Artifact Registry. The process includes building the Docker image from a Dockerfile, tagging it with the specified repository details, and pushing it to the cloud repository, making it ready for deployment to Cloud Run." src="https://cdn-images-1.medium.com/max/1024/1*KjZvOyW5QsyKAiDvMGV86A.png" /><figcaption>Building and pushing a Docker container to Google Cloud’s Artifact Registry for deployment</figcaption></figure><p><strong>Task 5- Deploy the Application to Cloud Run and Test: </strong>I used the gcloud run deploy command to deploy the application, specifying parameters like the service name, image location, and environment variables.</p><p>Ensure you have set the necessary environment variables for your Google Cloud project and region.</p><pre>export PROJECT=&#39;your-project-id&#39;<br>export REGION=&#39;your-region&#39;<br>export AR_REPO=&#39;gemini-repo&#39;<br>export SERVICE_NAME=&#39;chef-streamlit-app&#39;</pre><p>Use the gcloud run deploy command to deploy the Docker image to Cloud Run:</p><pre>gcloud run deploy &quot;$SERVICE_NAME&quot; \<br>  --port=8080 \<br>  --image=&quot;$REGION-docker.pkg.dev/$PROJECT/$AR_REPO/$SERVICE_NAME&quot; \<br>  --allow-unauthenticated \<br>  --region=$REGION \<br>  --platform=managed \<br>  --project=$PROJECT \<br>  --set-env-vars=GOOGLE_CLOUD_PROJECT=$PROJECT,GOOGLE_CLOUD_REGION=$REGION</pre><figure><img alt="Terminal output showing the execution of a gcloud run deploy command to deploy a service, including enabling APIs, deploying the container, creating a service and revision, and the final service URL." src="https://cdn-images-1.medium.com/max/1024/1*JI0b00_qRmDCaM4NyoQ4TA.png" /><figcaption>Terminal output showing the successful deployment of a service to Cloud Run.</figcaption></figure><p>Once deployment is done, we get a public URL, we can visit the URL to check how the app works. The UI is same as the Streamlit app we got in Task 3.</p><h3>Conclusion</h3><p>The challenge lab was a rewarding experience that allowed me to showcase my skills in developing Gen AI applications. By completing this lab, I gained confidence in my ability to tackle complex problems using generative AI and Streamlit. This lab marked a significant milestone in my journey with generative AI and solidified my readiness to apply these skills in future projects. I earned <a href="https://www.credly.com/badges/2d7ba31c-cec6-408f-b64c-c69fb5f50285/public_url"><strong>Develop GenAI Apps with Gemini and Streamlit Skill Badge</strong></a><strong>.</strong></p><p>The entire process can be represented by the following illustration :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*DM52vSKbhTONxyoPsUaO3Q.png" /><figcaption>Using Streamlit and Gemini SDK for user queries</figcaption></figure><p>#GenAI #Streamlit #GoogleCloud #AIAppDevelopment #MachineLearning #VertexAI #Docker #CloudRun #PromptEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f283bbd06865" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting Effective Prompts: A Journey through Prompt Design in Vertex AI]]></title>
            <link>https://medium.com/@mridulmishra8/crafting-effective-prompts-a-journey-through-prompt-design-in-vertex-ai-d3c8a9995991?source=rss-a60f2f7fbae2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3c8a9995991</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[Mridul Mishra]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 09:35:21 GMT</pubDate>
            <atom:updated>2025-04-25T11:07:29.789Z</atom:updated>
            <content:encoded><![CDATA[<p>In the sorcery of LLMs, prompts are the wands that conjure reality from imagination. With just a few well-chosen words, you can guide powerful language models to create content that aligns with your vision, whether you’re crafting marketing copy, designing engaging social media posts, or developing interactive applications. This transformative capability is at the heart of LLMs like Gemini, where the art of prompt design meets the science of generative AI.</p><p>In this article, we’ll explore the <a href="https://www.cloudskillsboost.google/course_templates/976">Prompt Design in Vertex AI course</a>, a comprehensive journey that teaches you how to harness the full potential of generative AI models like Gemini. From mastering the basics of prompt engineering to experimenting with advanced techniques, you’ll learn how to turn your imaginative ideas into tangible, high-quality outputs.</p><p>A<strong> prompt is a carefully crafted input provided to a language model, designed to elicit a specific type of response</strong>. Think of it as a set of instructions or a query that guides the AI model to generate the desired output. In the context of generative AI, prompts are the key to unlocking the full potential of language models like Gemini.</p><h3>What Does a Prompt Do?</h3><p>Prompts serve several critical functions in the interaction between humans and AI models:</p><ol><li><strong>Guiding the Model</strong>: Prompts direct the AI model to focus on a specific task or topic. They help the model understand what kind of response is expected, whether it’s a descriptive paragraph, a creative story, a technical explanation, or something else.</li><li><strong>Enhancing Relevance</strong>: By providing clear and specific instructions, prompts ensure that the AI-generated content is relevant and aligned with the user’s needs. This is crucial for applications like content creation, customer support, and data analysis.</li><li><strong>Improving Quality</strong>: Well-crafted prompts can significantly enhance the quality of the AI-generated output. They help reduce ambiguity, minimize errors, and produce more accurate and useful results.</li><li><strong>Customizing Output</strong>: Prompts allow users to customize the style, tone, and format of the AI-generated content. This flexibility is essential for creating content that fits different contexts and audiences.</li></ol><h3>Basic Components of a Prompt:</h3><p>A well-structured prompt typically includes the following components:</p><ol><li><strong>Task Definition: </strong>Clearly state the task you want the AI model to perform. This could be as simple as “Describe the image” or as complex as “Generate a detailed product description for a durable backpack designed for hikers.”</li><li><strong>Context:</strong> Provide any necessary background information or context that the model needs to understand the task. This could include details about the subject, the intended audience, or the desired outcome.</li><li><strong>Examples:</strong> Include examples to guide the model’s understanding and improve response quality. Examples can be particularly useful in tasks like classification, summarization, or creative writing.</li><li><strong>Parameters:</strong> Specify any parameters that control the model’s behavior, such as temperature (which affects randomness) or token limit (which controls the length of the output).</li><li><strong>Constraints:</strong> Define any constraints or rules that the model should follow. This could include limitations on the length of the response, the style of writing, or the inclusion of specific keywords.</li></ol><p>(Points 4 and 5 are for programmers , a normal user should focus on 1–3)</p><h4>Now I will discuss the learnings of the course : Prompt Design in Vertex AI course</h4><h3><strong>Lab 1: Generative AI with Vertex AI: Prompt Design</strong></h3><p>This lab provides a comprehensive introduction to the foundational skills of prompt engineering. This lab emphasizes the importance of crafting <strong>prompts that are concise, specific, and well-defined</strong>, ensuring that the AI model generates responses that align with your intended goals. Here’s a detailed summary of the key learnings from Lab 1:</p><p><strong>Best Practices for Prompt Engineering:</strong></p><p>1.<strong>Be Concise :</strong></p><ul><li>Not Recommended: Verbose prompts can lead to confusion and irrelevant responses.</li></ul><figure><img alt="A code snippet written in Python defining a variable prompt with the value: “What do you think could be a good name for a flower shop that specializes in selling bouquets of dried flowers more than fresh flowers?”" src="https://cdn-images-1.medium.com/max/819/1*HNuUEced74A6T9bzL0UxMA.png" /></figure><ul><li>Recommended: Concise prompts are more effective.</li></ul><figure><img alt=": A Python code snippet shown in a dark-themed editor. It defines a variable prompt with the string: “Suggest a name for a flower shop that sells bouquets of dried flowers”" src="https://cdn-images-1.medium.com/max/819/1*k6cFssANv2t-VFpdMINa7g.png" /></figure><p>2<strong>.Be Specific and Well-Defined:</strong></p><ul><li>Not Recommended: Generic prompts may not yield the desired level of detail.</li></ul><figure><img alt="A Python code snippet thatdefines a variable prompt containing the string: “ Tell me about earth”" src="https://cdn-images-1.medium.com/max/822/1*30wesDDU6wi0wIQXU4YrRg.png" /></figure><ul><li>Recommended: Specific prompts provide clearer and more relevant responses.</li></ul><figure><img alt="A Python code snippet thatdefines a variable prompt containing the string: “Generate a list of ways that makes Earth unique compared to other planets”" src="https://cdn-images-1.medium.com/max/824/1*tQjST9c8FGhZ79gj3JCo4g.png" /></figure><p>3.<strong>Ask One Task at a Time:</strong></p><ul><li>Not Recommended: Combining multiple questions in one prompt can lead to incomplete or irrelevant answers.</li></ul><figure><img alt="A code snippet written in Python defining a variable prompt with the value: “What’s the best method of boiling water and why is the sky blue?”" src="https://cdn-images-1.medium.com/max/828/1*45mNYiOlut5BA5YVrLQGcA.png" /></figure><ul><li>Recommended: Separate prompts for each task ensure focused responses.</li></ul><figure><img alt="A code snippet written in Python defining the variable prompt twice, first with the value: “What’s the best method of boiling water?” and then with the value: “Why is the sky blue?”" src="https://cdn-images-1.medium.com/max/820/1*z11T5ZMkyeufNwP5hnz5GQ.png" /></figure><p>4.<strong>Watch Out for Hallucinations:</strong></p><ul><li>LLMs can generate responses that are not grounded in reality, known as “hallucinations.”</li><li>Providing system instructions can help reduce irrelevant responses and hallucinations.</li></ul><figure><img alt="A code snippet written in Python defining a variable system_instruction as a list containing strings with instructions for an AI chatbot. The instructions guide the chatbot to assist with travel-related queries and to verify if a question aligns with its mission before answering. If not, it should respond with, “Sorry I can’t answer that question.”" src="https://cdn-images-1.medium.com/max/833/1*cokEEF8fTt4stBHTcbdD3Q.png" /></figure><p>5.<strong> Turn Generative Tasks into Classification Tasks:</strong></p><ul><li>Generative Tasks: Open-ended prompts lead to higher variability in responses.</li></ul><figure><img alt="A code snippet written in Python defining a variable prompt with the value: “I’m a high school student. Recommend me a programming activity to improve my skills.”" src="https://cdn-images-1.medium.com/max/825/1*acfQNDvKHKN5nM-NSKeIew.png" /></figure><ul><li>Classification Tasks: Structured prompts with choices reduce variability and improve control.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*OZm85wYhgcPZ78NVwFnbGQ.png" /></figure><p>6. <strong>Improve Response Quality by Including Examples</strong></p><ul><li>Zero-shot Prompting: No examples provided, leading to more open-ended and creative responses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*GRZ9Mlmk6DNXZxyh5alWXw.png" /></figure><ul><li>One-shot Prompting: One example provided to guide the response.</li></ul><figure><img alt="A code snippet written in Python defining a variable prompt with the value: “Decide whether a Tweet’s sentiment is positive, neutral, or negative. Tweet: I loved the new YouTube video you made! Sentiment: positive Tweet: That was awful. Super boring angry emoji Sentiment:”" src="https://cdn-images-1.medium.com/max/819/1*9TyXbnLFb7OTrE-XyvvQNA.png" /></figure><ul><li>Few-shot Prompting: Multiple examples provided for more consistent and predictable responses.</li></ul><figure><img alt="Python code snippet that defines a variable prompt with string value : “Decide whether a Tweet’s sentiment is positive, neutral, or negative.
 Tweet: I loved the new YouTube video you made!
 Sentiment: positive
 Tweet: That was awful. Super boring 😠
 Sentiment: negative
 Tweet: Something surprised me about this video — it was actually original. It was not the same old recycled stuff that I always see. Watch it — you will not regret it.
 Sentiment:”" src="https://cdn-images-1.medium.com/max/824/1*FU-UGvR1QNHMiW7DPwi_aQ.png" /></figure><p><strong>This lab intoduces two very important concepts of prompts :</strong></p><ol><li><strong>System Instructions: </strong>System instructions are initial directives that shape the behavior and responses of AI models. They are processed by the model before it processes the main prompt, providing context and guidelines that influence how the model interprets and responds to subsequent inputs. System instructions are crucial for customizing the <strong>persona(</strong>how should the LLM act e.g. a data analyst), <strong>format</strong>, <strong>tone (</strong>such as formal, casual, friendly, or authoritative<strong>)</strong>, and <strong>specific task rules(</strong>specific rules or constraints for the task, such as limiting the response length, requiring the inclusion of certain keywords) of the AI model.</li><li><strong>Examples: </strong>Sample inputs and outputs provided within the prompt to guide the AI model’s understanding and improve the quality of the response. They help the model learn the desired pattern or style, resulting in more consistent and predictable outputs.</li></ol><h3><strong>Lab 2: Get Started with Vertex AI Studio</strong></h3><p>This lab delves into the practical application of prompt engineering using Vertex AI Studio. This lab focuses on how to use the platform to analyze images, design prompts, and explore multimodal capabilities directly within the Google Cloud console. We implemented the conceptes learned in Lab 1.</p><p>Here’s a detailed summary of the key learnings from Lab 2:</p><figure><img alt="Screenshot of the Google Cloud Vertex AI interface for creating prompts, showing options like Company chatbot, Image Editing, and Question answering about an image for the Gemini 2.0 Flash model." src="https://cdn-images-1.medium.com/max/1024/1*0D3C38YXLMp3039Bib0C8w.png" /><figcaption>Exploring prompt creation options for the Gemini 2.0 Flash model within the Google Cloud Vertex AI platform, showcasing examples like chatbot, image editing, and question answering.</figcaption></figure><ul><li><strong>Task 1: Analyze Images with Gemini:</strong></li></ul><p>Objective: Use Gemini to analyze an image and extract information from it.</p><p>I used use Gemini to analyze an image and extract information from it. I designed prompts for classification, extraction, and generation and analysis of text.</p><ul><li><strong>Task 2: Explore Multimodal Capabilities:</strong></li></ul><p>Objective: Use Gemini to process videos and generate descriptive text.</p><p>Gemini is capable of processing and working with videos, images, text. I worked on a video file and designed prompts to generate titles, detailed descriptions, and other relevant information from the video.</p><ul><li><strong>Task 3: Design prompts with examples:</strong></li></ul><p>Here I created prompts that include examples to guide the AI model’s understanding and improve response quality. I created prompts that include examples to guide the AI model’s understanding and improve response quality.</p><figure><img alt="Screenshot of an interface for providing model examples, showing input text fields like “A well-made and entertaining film” and corresponding output labels like “positive”, “negative”, and “neutral”." src="https://cdn-images-1.medium.com/max/1024/1*BPkGg03FuqbE1Vfo6uqKFg.png" /><figcaption>Providing examples of input and desired output to train a model, demonstrating sentiment analysis with movie review examples labeled as positive, negative, and neutral.</figcaption></figure><figure><img alt="Screenshot of a text interface with an input labeled “{Input} The color of the sky is” and a prompt below that says “Answer the following questions,” with a blinking cursor in a text box." src="https://cdn-images-1.medium.com/max/1024/1*uLp0jVgIU_lxSlxwP2CPMg.png" /><figcaption>An interface showing an input prompt</figcaption></figure><ul><li><strong>Task 4: Design prompts with context:</strong></li></ul><p>Objective: Use system instructions to shape the model’s behavior and responses.</p><p>I added system instructions for the model and it responded based on the context provided.</p><figure><img alt="Screenshot of a system instructions interface for an AI, defining a persona named Roy who is an IT support technician and is instructed to only respond with “Have you tried turning it off and on again?”. Below, a user asks “My computer is so slow! What should I do?” and the AI responds as instructed." src="https://cdn-images-1.medium.com/max/1024/1*HH5vbl4qiI9FH2BTgOF9gQ.png" /><figcaption>system instructions to define an AI’s persona and response style</figcaption></figure><h3><strong>Lab 3: Getting Started with the Gemini API in Vertex AI</strong></h3><p>Lab 3 focuses on exploring and modifying the Python code for the image analysis prompts you created in Vertex AI Studio. This lab provides a deeper understanding of how to implement generative AI capabilities using code, allowing you to test and refine your prompts in a more flexible environment. Basically, the tasks done in above labs are achieved through the Python SDK. Here’s a summary of tasks executed in Lab 3:</p><ul><li>Setting up the environment for running the code.</li><li>Setting up the notebook and Gemini model to use.</li><li>Generating response based on text</li></ul><figure><img alt="Screenshot showing Python code that defines a prompt to get 10 tech industry trends under 5 words each, followed by the output which is a numbered list of trends such as “Generative AI explosion”, “Cloud cost optimization”, and “Quantum computing progress”." src="https://cdn-images-1.medium.com/max/1024/1*FJPiuadcBVLgkdwBGEH0Eg.png" /><figcaption>programmatically generate a list of tech industry trends using a language model based on a specific prompt</figcaption></figure><ul><li>Generating Response based a local image and text</li></ul><figure><img alt="An image of a tabby cat standing in the snow, followed by a prompt “Describe this image?” and a generated response with a detailed description of the cat." src="https://cdn-images-1.medium.com/max/1024/1*VtvYa4WLnxjI4j_N-aItOg.png" /><figcaption>Image Analysis with Prompt</figcaption></figure><ul><li>Generating Response based on multiple images and text.</li><li>Generate text from a video file</li><li>Direct analysis of publicly available web media</li></ul><h3><strong>Lab 4: Challenge Lab</strong></h3><p>Lab 4 is a challenge lab designed to test ability to apply the skills learned throughout the course. In this lab, a scenario and a set of tasks to complete on your own, using the knowledge and techniques acquired. This lab is an excellent opportunity to demonstrate proficiency in prompt engineering and generative AI implementation.</p><p><strong>Challenge Scenario : </strong>You’re a member of an educational content startup specializing in engaging learners with the natural world. You’ve formed a partnership with Cymbal Direct, an online retailer launching a new line of outdoor gear and apparel designed to encourage young people to explore and connect with nature.</p><p>Cymbal Direct wants to create a marketing campaign for its new product line that leverages the power of generative AI. Your task is to help them develop a set of tools within Google Cloud’s Vertex AI platform that will streamline the generation of the following:</p><ul><li><strong>Evocative Product Descriptions</strong>: using image analysis to inspire short, descriptive text that captures the essence of their products and the feeling of being in nature.</li><li><strong>Catchy Taglines</strong>: focused on highlighting product features, the target audience, and the desired emotional response.</li></ul><p>Task 1 and Task 2 to be performed in the Google cloud studio, using the Create Prompt feature of Vertex Ai module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r4N7lqExKMMLj0G_7ytDCw.png" /><figcaption>Task 1: Build a Gemini image analysis tool</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZgQAETO85O86w54P2u9kfQ.png" /><figcaption>Task 2: Build a Gemini tagline generator</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XER7KVQ7pvT5wF55CwUuZg.png" /><figcaption>Task 3 : Experiment with image analysis code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AbVeXUO-54Z_KJTimDcww.png" /><figcaption>Task 4 : Experiment with tagline generation code</figcaption></figure><h3><strong>Summary and Example prompt</strong></h3><p>So, to summarize, through this course, I’ve gained the skills to craft effective prompts and leverage generative AI models like Gemini. I’ve learned to analyze images, generate descriptive text, and create customizable taglines, all while experimenting with code in Jupyter notebooks. By mastering prompt engineering and utilizing Vertex AI Studio, I’ve unlocked the full potential of generative AI for creative and practical applications, enhancing my ability to produce high-quality, relevant, and controlled content.</p><p>Putting It All Together: A Practical Use-Case :</p><h4>Scenario:</h4><p>You are working with a travel company that specializes in adventure tours. They want to create a marketing campaign for a new line of eco-friendly adventure tours designed to encourage young travelers to explore natural wonders while minimizing their environmental impact. Your task is to help them develop a set of tools within Google Cloud’s Vertex AI platform to generate engaging marketing content.</p><p><strong>Ideal Prompt:</strong></p><p><strong>Task Definition:</strong> Generate a catchy tagline for an eco-friendly adventure tour designed for young travelers.</p><p><strong>Context:</strong> The tagline should evoke a sense of adventure and environmental responsibility. It should be suitable for social media ads and product descriptions.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_WV4MQnMg5RG2XYeZd_CQ.png" /></figure><p>Parameters:</p><ul><li>Temperature: 0.7 (to balance creativity and relevance)</li><li>Token Limit: 50 (to ensure a concise response)</li></ul><p>Constraints:</p><ul><li>Include the keyword “eco-friendly.”</li><li>Keep the tagline under 10 words.</li></ul><p>So, a prompt for the scenario, applying all the learnings from the course is as under :</p><figure><img alt="Code snippet showing a Python string variable named ‘prompt’ containing a request to generate an eco-friendly adventure tour tagline." src="https://cdn-images-1.medium.com/max/873/1*578-Og7OTwzwULamLe8VVg.png" /></figure><p>I earned <a href="https://www.credly.com/badges/6f29d980-8152-4aa8-852a-d068439874d3/public_url">my Google Cloud Skill Badge</a> in Machine Learning domain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xHy2Qzu7yz_16dEC" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3c8a9995991" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>