Skip to main content
An Agent using the Gemini image generation tool.
Google discontinued the source’s imagen-4.0-generate-preview-05-20 endpoint. The source also uses the removed Agent.run_response attribute and passes raw image bytes to a base64 decoder. Apply all three edits below before running. See the Vertex AI release notes.
imagen_tool_advanced.py

Run the Example

1

Set up your virtual environment

2

Install dependencies

3

Export environment variables

4

Authenticate with Google Cloud

Sign in with Application Default Credentials:
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 the example

Save the code above as imagen_tool_advanced.py, then run:
Full source: cookbook/90_models/google/gemini/imagen_tool_advanced.py