Projects · · 4 min read
add image generation to python chatbot with Gemini
I walk through how I added on‑the‑fly image generation to my Python chatbot using Gemini, Supabase storage, and a few simple libraries.
When I first heard that Gemini can produce images from text prompts, I wondered how I could let my Python chatbot create pictures for users on demand. The search phrase "add image generation to python chatbot" led me to a few scattered examples, but nothing that fit the low‑cost, free‑tier setup I use in Pundri. In this post I share the step‑by‑step process I followed, the hiccups I hit, and the practical code snippets that finally let my bot return a generated image URL to the chat window.
Why add image generation to python chatbot?
My chatbot already handles text queries, voice commands, PDF ingestion, and sentiment analysis. Adding images makes the experience richer for a few reasons: 1. Visual explanations help users grasp concepts faster, especially when talking about places, diagrams, or product ideas. 2. It opens up new use‑cases like creating quick mock‑ups for a marketing pitch or generating a meme for a friendly conversation. 3. The Gemini API lets me experiment with AI‑generated art without paying for a separate service, keeping the whole stack under one roof. If you are curious about how this ties into my other projects, check out my guide on adding voice commands to my Python chatbot and the walkthrough on adding PDF ingestion.
Prerequisites and tools
- Python 3.10+ installed locally.
- VS Code with Claude Code extension for AI‑assisted coding.
- A Supabase project (free tier) for storing generated images.
- Gemini API key (I used the free quota from Google AI Studio).
- The `requests`, `python-dotenv`, and `supabase` Python packages.
If you haven’t set up a Supabase edge function before, my post on a simple guide to using Supabase Edge Functions with Python walks you through the basics.
Step‑by‑step: add image generation to python chatbot
Below is the workflow I used. Feel free to adapt it to your own bot framework.
- Create a new function `generate_image(prompt: str) -> str` that calls the Gemini image model.
- Store the returned image bytes in a Supabase bucket and get a public URL.
- Modify the chatbot’s response handler to detect a special command like `/image <description>` and call the function.
- Return the image URL back to the chat client, rendering it as an inline picture.
import os, requests
from supabase import create_client, Client
from dotenv import load_dotenv
load_dotenv()
# Initialise Supabase client
url: str = os.getenv("SUPABASE_URL")
key: str = os.getenv("SUPABASE_ANON_KEY")
supabase: Client = create_client(url, key)
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
GEMINI_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent"
def generate_image(prompt: str) -> str:
"""Call Gemini to create an image and upload it to Supabase.
Returns a public URL that can be sent back to the chat client.
"""
payload = {
"contents": [{"role": "user", "parts": [{"text": prompt}]}],
"generationConfig": {"responseMimeType": "image/png"},
}
headers = {"Content-Type": "application/json", "x-goog-api-key": GEMINI_API_KEY}
response = requests.post(GEMINI_ENDPOINT, json=payload, headers=headers)
response.raise_for_status()
image_data = response.content
# Upload to Supabase storage bucket named 'chatbot-images'
file_name = f"{int(time.time())}.png"
supabase.storage.from_("chatbot-images").upload(file_name, image_data)
public_url = supabase.storage.from_("chatbot-images").get_public_url(file_name)
return public_url
# Example usage inside the chat handler
if user_message.startswith("/image"):
description = user_message[len("/image"):].strip()
img_url = generate_image(description)
send_message(f"Here’s your image: {img_url}")
A few things I learned while writing this function: * Gemini returns raw image bytes when you set `responseMimeType` to `image/png`. I initially tried `image/jpeg` and got a JSON error. * Supabase’s `upload` method expects a file‑like object, so passing the raw bytes works directly. * The public URL is instantly accessible, which is perfect for a quick demo, but for production you might want signed URLs or a CDN. If you’re new to environment variables, see my post on setting up a Python AI development environment for a quick walkthrough.
Handling edge cases and user expectations
Generating images can be slower than plain text replies. I added a simple loading message (`Bot is sketching…`) so the user knows something is happening. Also, I capped the prompt length at 100 characters to avoid hitting Gemini’s request size limits. Another hiccup was the occasional 429 Too Many Requests error when I hit the free quota too quickly. To mitigate this, I introduced a basic rate‑limit cache that stores recent prompts for 30 seconds and returns the same image if the request repeats.
"AI tools are only as useful as the workflow you build around them" – a reminder I keep in mind whenever I add a new feature.
Testing the feature locally
I run the chatbot inside VS Code’s integrated terminal and use `ngrok` to expose a temporary HTTPS endpoint. This lets the chat client (a simple Streamlit UI) load images without dealing with CORS. The whole setup costs less than $0.10 a month on Supabase’s free tier.
If you want to see the full repository, check out my projects page for a link to the code: my projects.
Takeaway
Adding image generation to a Python chatbot is surprisingly straightforward when you already use Gemini for text. The biggest gains come from reusing the same Supabase bucket for storage and keeping the API calls lightweight. I still have room to improve – for example, adding style presets or letting users up‑vote favorite images – but the core feature works reliably and makes the bot feel a lot more interactive.
Frequently asked questions
Can Gemini generate images for free?
Gemini offers a limited free quota that includes image generation. I stay within that quota by limiting prompt length and caching recent requests.
Do I need a paid Supabase plan to store generated images?
No, the free tier provides enough storage for small projects. I store each image in a bucket and serve it via a public URL, which works fine for a personal chatbot.
How do I handle slow image generation in the chat UI?
Show a temporary loading message like "Bot is sketching…" and consider rate‑limiting requests. Caching identical prompts for a short period also reduces repeated calls.
Is the code compatible with other AI providers?
The structure is generic: call the provider’s image endpoint, upload the bytes to Supabase (or another storage), and return the URL. You would only need to replace the request payload and endpoint.