Advanced Imagen Tool with Vertex AI

Code

1"""🔧 Example: Using the GeminiTools Toolkit for Image Generation
2
3An Agent using the Gemini image generation tool.
4
5Make sure to set the Vertex AI credentials. Here's the authentication guide: https://cloud.google.com/sdk/docs/initializing
6
7"""
8
9from kern.agent import Agent
10from kern.models.openai import OpenAIResponses
11from kern.tools.models.gemini import GeminiTools
12from kern.utils.media import save_base64_data
13
14agent = Agent(
15 model=OpenAIResponses(id="gpt-5.2"),
16 tools=[
17 GeminiTools(
18 image_generation_model="imagen-4.0-generate-preview-05-20", vertexai=True
19 )
20 ],
21)
22
23agent.print_response(
24 "Cinematic a visual shot using a stabilized drone flying dynamically alongside a pod of immense baleen whales as they breach spectacularly in deep offshore waters. The camera maintains a close, dramatic perspective as these colossal creatures launch themselves skyward from the dark blue ocean, creating enormous splashes and showering cascades of water droplets that catch the sunlight. In the background, misty, fjord-like coastlines with dense coniferous forests provide context. The focus expertly tracks the whales, capturing their surprising agility, immense power, and inherent grace. The color palette features the deep blues and greens of the ocean, the brilliant white spray, the dark grey skin of the whales, and the muted tones of the distant wild coastline, conveying the thrilling magnificence of marine megafauna."
25)
26response = agent.get_last_run_output()
27if response and response.images:
28 save_base64_data(str(response.images[0].content), "tmp/baleen_whale.png")
29
30"""
31Example prompts to try:
32- A horizontally oriented rectangular stamp features the Mission District's vibrant culture, portrayed in shades of warm terracotta orange using an etching style. The scene might depict a sun-drenched street like Valencia or Mission Street, lined with a mix of Victorian buildings and newer structures.
33- Painterly landscape featuring a simple, isolated wooden cabin nestled amongst tall pine trees on the shore of a calm, reflective lake.
34- Filmed cinematically from the driver's seat, offering a clear profile view of the young passenger on the front seat with striking red hair.
35- A pile of books seen from above. The topmost book contains a watercolor illustration of a bird. VERTEX AI is written in bold letters on the book.
36"""

Usage

Set up your virtual environment

1uv venv --python 3.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Set up Vertex AI authentication

Follow the authentication guide to set up Vertex AI credentials.

1gcloud auth application-default login

Set your API keys

1export GOOGLE_API_KEY=xxx
2export OPENAI_API_KEY=xxx
3export GOOGLE_CLOUD_PROJECT=your-project-id

Install dependencies

1uv pip install -U google-genai openai kern-ai

Run Agent

1python cookbook/11_models/google/gemini/imagen_tool_advanced.py