# Text-to-Image Generation with Gemini on Vertex AI (Solution)

## Overview

In a challenge lab you’re given a scenario and a set of tasks. Instead of following step-by-step instructions, you will use the skills learned from the labs in the course to figure out how to complete the tasks on your own! An automated scoring system (shown on this page) will provide feedback on whether you have completed your tasks correctly.

When you take a challenge lab, you will not be taught new Google Cloud concepts. You are expected to extend your learned skills, like changing default values and reading and researching error messages to fix your own mistakes.

To score 100% you must successfully complete all tasks within the time period! Are you ready for the challenge?

## Challenge scenario

**Scenario:** You're a developer at Cymbal Solutions which is an educational technology company that provides online tutoring and educational resources. They want to create an interactive science tutoring assistant to help students with questions related to astronomy and other scientific topics. They decide to use Google Cloud’s Vertex AI SDK to build a chat-based solution that can provide informative answers. you need to finish the below tasks:

**Task:** Develop a Python function named `get_chat_response(prompt)`. This function should invoke the `gemini-2.5-flash` model using the supplied `prompt`, which will uses Gemini's ability to understand the text prompt and use it to build an AI Image.

For this challenge, use these questions in the prompt: **"Hello! What are all the colors in a rainbow?"** and **"What is Prism?"**.

**Follow these steps to interact with the Generative AI APIs using Vertex AI Python SDK.**

1. Click **File &gt; New File** to open a new file within the Code Editor.
    
2. Write the Python code to use Google's Vertex AI SDK to interact with the pre-trained Text Generation AI model.
    
3. Create and save the python file.
    
4. Execute the Python file by invoking the below command by replacing the **FILE\_NAME** inside the terminal within the Code Editor pane to view the output.
    

```apache
/usr/bin/python3 /FILE_NAME.py
```

**Note:** You can ignore any warnings related to Python version dependencies.

Click **Check my progress** to verify the objective.

Send the text prompt requests to GenAI and receive the chat responses

---

## Solution of Lab

%[https://youtu.be/i6yyB1XbfiA] 

Create a file **eplus.py**

```python
import os
import vertexai
from vertexai.generative_models import GenerativeModel, GenerationConfig

def get_chat_response(prompt: str) -> str:
    PROJECT_ID = "qwiklabs-gcp-04-00e01999fb87"
    LOCATION = "us-west1"
    if not PROJECT_ID:
        raise RuntimeError("Missing PROJECT_ID. Set GOOGLE_CLOUD_PROJECT or DEVSHELL_PROJECT_ID.")

    vertexai.init(project=PROJECT_ID, location=LOCATION)

    model = GenerativeModel("gemini-2.5-flash")

    config = GenerationConfig(
        temperature=0.7,
        max_output_tokens=1024,
        response_modalities=["TEXT", "IMAGE"],
    )

    response = model.generate_content(prompt)

    text_out = (getattr(response, "text", "") or "").strip()

    imgs = getattr(response, "generated_images", None)
    first_img = None
    if imgs is not None:
        try:
            first_img = next(iter(imgs), None)
        except TypeError:
            first_img = None

    if first_img is not None and hasattr(first_img, "image_bytes"):
        with open("output.png", "wb") as f:
            f.write(first_img.image_bytes)
        text_out += "\n[Image saved to: output.png]"

    return text_out

if __name__ == "__main__":
    prompt = (
        "You are an interactive science tutoring assistant.\n\n"
        "Question 1: Hello! What are all the colors in a rainbow?\n"
        "Question 2: What is Prism?\n\n"
        "After answering, generate an educational image showing a prism "
        "splitting white light into a rainbow."
    )
    print(get_chat_response(prompt))
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1769477547856/3f039b1e-5f5c-428f-946d-87bdec704b7f.png align="center")

```apache
/usr/bin/python3 /eplus.py
```

**Alternative Solution**

``apache
curl -LO raw.githubusercontent.com/ePlus-DEV/storage/refs/heads/main/labs/text-to-image-generation-with-gemini-on-vertex-ai-solution/lab.sh
source lab.sh
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1769477719956/3f816c37-094c-4220-9691-cb7f282275a3.png align="center")

```apache
python3 main.py
```

