Google Gemini: non-chat script

For my Gemini scripts you will need a Gemini API key: don’t worry, they’re easy to obtain. Go HERE to apply for your key. At the time of writing, some users may need to use a US proxy to obtain the API key. If the link doesn’t work, Google “Gemini API key” for the correct page.

This script allows you to send sequential queries to Gemini, drawn from the input.csv file. The answers are saved in the output.csv file. This is not a chat, so the prompts are responded to independently.


This is similar to the ChatGPT script, except that this does not use the OpenAI API, and therefore costs nothing to run. It does require a bit more setting up. Being able to send queries automatically to AI Chatbots means you can create high volumes of good quality content without intervention. For example, you can use this script to ask Gemini to write a product review in one shot, and then repeat the prompt for different products.


  1. You need a Gemini account
  2. You need a Gemini API key. Apply here:
  3. Now install the Gemini API
pip install -q -U google-generativeai

How to use it

  1. Save the script below in the folder of your choice.
  2. Create an input.csv file, which contains the prompts in the first column to be sent to Gemini
  3. The output is saved as output.csv
import pathlib
import textwrap
import csv
import time

import google.generativeai as genai

#  !!! CAUTION: Hardcoding API keys is highly discouraged !!!
api_key = "YOU_API_KEY"
model = genai.GenerativeModel('gemini-pro')

# Rate limiting (adjust sleep time if needed)

def process_query(query):
    """Sends a query to Gemini and handles potential rate limiting"""
        response = model.generate_content(query)
        return response.text
    except genai.exceptions.RateLimitExceededError as e:
        print(f"Rate limit exceeded. Waiting {RATE_LIMIT_SLEEP_SECONDS} seconds...")
        return process_query(query)  # Retry the query

# Load queries from input.csv
input_filepath = pathlib.Path("input.csv")
with'r', newline='') as csvfile:
    reader = csv.reader(csvfile)
    queries = list(reader)  

# Process queries and save responses
output_filepath = pathlib.Path("output.csv")
with'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    for query in queries:
        response = process_query(query[0])  # Assume query in the first column
        writer.writerow([query[0], response])
        print(f"Query: {query[0]}\nResponse: {textwrap.shorten(response, width=80)}\n")