Skip to main content

Code

imagen_tool_advanced.py
The source uses the retired imagen-4.0-generate-preview-05-20 model, the removed Agent.run_response accessor, and raw image bytes where save_base64_data expects base64. Apply all three edits below before running. Google will shut down Imagen 4 on August 17, 2026. Migrate to the Gemini image-generation API, which uses generate_content, before that date.

Usage

1

Set up your virtual environment

2

Set up Vertex AI authentication

Follow the authentication guide to set up Vertex AI credentials.
3

Set environment variables

4

Install dependencies

5

Update the Imagen model

Replace imagen-4.0-generate-preview-05-20 with imagen-4.0-generate-001 in the saved file.
6

Use the v2 run output accessor

Replace response = agent.run_response with response = agent.get_last_run_output() in the saved file.
7

Encode the image bytes

Add import base64, then replace save_base64_data(str(response.images[0].content), "tmp/baleen_whale.png") with save_base64_data(base64.b64encode(response.images[0].content).decode("ascii"), "tmp/baleen_whale.png") in the saved file.
8

Run Agent

Save the code above as imagen_tool_advanced.py, then run: