Loading...
No results found.

    Build Real World AI Applications with Gemini and Imagen

    Test and share your knowledge with our community!
    done
    Get access to over 700 hands-on labs, skill badges, and courses

    Build an application to send Chat Prompts using the Gemini model

    Lab 15 minutes universal_currency_alt No cost show_chart Introductory
    info This lab may incorporate AI tools to support your learning.
    Test and share your knowledge with our community!
    done
    Get access to over 700 hands-on labs, skill badges, and courses

    bb-ide-genai-003

    Google Cloud self-paced labs logo

    Overview

    • Labs are timed and cannot be paused. The timer starts when you click Start Lab.
    • The included cloud terminal is preconfigured with the gcloud SDK.
    • Use the terminal to execute commands and then click Check my progress to verify your work.

    Objective

    Generative AI on Vertex AI (also known as genAI or gen AI) gives you access to Google's large generative AI models so you can test, tune, and deploy them for use in your AI-powered applications. In this lab, you will:

    • Connect to Vertex AI (Google Cloud AI platform): Learn how to establish a connection to Google's AI services using the Vertex AI SDK.
    • Load a pre-trained generative AI model -Gemini: Discover how to use a powerful, pre-trained AI model without building one from scratch.
    • Send text to the AI model: Understand how to provide input for the AI to process.
    • Extract chat responses from the AI: Learn how to handle and interpret the chat responses generated by the AI model.
    • Understand the basics of building AI applications: Gain insights into the core concepts of integrating AI into software projects.

    Working with Generative AI

    After starting the lab, you will get a split pane view consisting of the Code Editor on the left side and the lab instructions on the right side. Follow these steps to interact with the Generative AI APIs using Vertex AI Python SDK.

    Chat responses without using stream:

    Streaming involves receiving responses to prompts as they are generated. That is, as soon as the model generates output tokens, the output tokens are sent. A non-streaming response to prompts is sent only after all of the output tokens are generated.

    First we'll explore the chat responses without using stream.

    Create a new file to get the chat responses without using stream:

    1. Click File->New File to open a new file within the Code Editor.
    2. Copy and paste the provided code snippet into your file.
    import vertexai from vertexai.generative_models import GenerativeModel, ChatSession import logging from google.cloud import logging as gcp_logging # ------ Below cloud logging code is for Qwiklab's internal use, do not edit/remove it. -------- # Initialize GCP logging gcp_logging_client = gcp_logging.Client() gcp_logging_client.setup_logging() project_id = "{{{ project_0.project_id | "your-project-id" }}}" location = "{{{ project_0.default_region | "REGION" }}}" vertexai.init(project=project_id, location=location) model = GenerativeModel("gemini-1.0-pro") chat = model.start_chat() def get_chat_response(chat: ChatSession, prompt: str) -> str: logging.info(f'Sending prompt: {prompt}') response = chat.send_message(prompt) logging.info(f'Received response: {response.text}') return response.text prompt = "Hello." print(get_chat_response(chat, prompt)) prompt = "What are all the colors in a rainbow?" print(get_chat_response(chat, prompt)) prompt = "Why does it appear when it rains?" print(get_chat_response(chat, prompt))
    1. Click File->Save, enter SendChatwithoutStream.py for the Name field and click Save.

    2. Execute the Python file by clicking the triangle icon on the top-right corner of Code Editor or by running the below command inside the terminal within the Code Editor pane to view the output.

    /usr/bin/python3 /home/student/SendChatwithoutStream.py

    Code Explanation

    • The code snippet is loading a pre-trained AI model called Gemini (gemini-1.0-pro) on Vertex AI.
    • The code calls the get_chat_response method of the loaded Gemini model.
    • The input to the method is a text prompt.
    • The code uses Gemini's ability to chat. It uses the text provided in the prompt to chat.

    Chat responses with using stream:

    Now we'll explore the chat responses using stream.

    Create a new file to get the chat responses with using stream:

    1. Click File->New File to open a new file within the Code Editor.
    2. Copy and paste the provided code snippet into your file.
    import vertexai from vertexai.generative_models import GenerativeModel, ChatSession import logging from google.cloud import logging as gcp_logging # ------ Below cloud logging code is for Qwiklab's internal use, do not edit/remove it. -------- # Initialize GCP logging gcp_logging_client = gcp_logging.Client() gcp_logging_client.setup_logging() project_id = "{{{ project_0.project_id | "your-project-id" }}}" location = "{{{ project_0.default_region | "REGION" }}}" vertexai.init(project=project_id, location=location) model = GenerativeModel("gemini-1.0-pro") chat = model.start_chat() def get_chat_response(chat: ChatSession, prompt: str) -> str: text_response = [] logging.info(f'Sending prompt: {prompt}') responses = chat.send_message(prompt, stream=True) for chunk in responses: text_response.append(chunk.text) return "".join(text_response) logging.info(f'Received response: {response.text}') prompt = "Hello." print(get_chat_response(chat, prompt)) prompt = "What are all the colors in a rainbow?" print(get_chat_response(chat, prompt)) prompt = "Why does it appear when it rains?" print(get_chat_response(chat, prompt))
    1. Click File->Save, enter SendChatwithStream.py for the Name field and click Save.

    2. Execute the Python file by clicking the triangle icon on the top-right corner of Code Editor or by running the below command inside the terminal within the Code Editor pane to view the output.

    /usr/bin/python3 /home/student/SendChatwithStream.py

    Code Explanation

    • The code snippet is loading a pre-trained AI model called Gemini (gemini-1.0-pro) on Vertex AI.
    • The code calls the get_chat_response method of the loaded Gemini model.
    • The code is using stream=True while sending the messages. The stream=True argument indicates that the responses should be streamed back, allowing for real-time processing.
    • The code uses Gemini's ability to understand prompts and have a stateful chat conversation.

    Try it yourself! Experiment with different prompts to explore Gemini's capabilities.

    Click Check my progress to verify the objective.

    Send the text prompt requests to Gen AI and receive a chat response

    Congratulations!

    You have completed the lab! Congratulations!!

    Copyright 2025 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

    Previous Next

    Before you begin

    1. Labs create a Google Cloud project and resources for a fixed time
    2. Labs have a time limit and no pause feature. If you restart it, you'll have to start from the beginning.
    3. On the top left of your screen, click Start lab to begin

    Use private browsing

    1. Copy the provided Username and Password for the lab
    2. Click Open console in private mode

    Sign in to the Console

    1. Sign in using your lab credentials. Using other credentials might cause errors or incur charges.
    2. Accept the terms, and skip the recovery resource page
    3. Don't click End lab unless you've finished the lab or want to restart it, as it will clear your work and remove the project

    This content is not currently available

    We will notify you via email when it becomes available

    Great!

    We will contact you via email if it becomes available

    One lab at a time

    Confirm to end all existing labs and start this one

    Setup your console before you begin

    Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
    Preview