Google Gemini: 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 linked queries to Gemini in a chat format, drawn from the chat.csv file. The answers are saved in the chatoutput.csv file. Unlike this script, this script is a continuous conversation, so the prompts are responded to as part of the same chat.
Usage
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 story outline, and then ask it to completre each chapter, prompt by prompt.
Prerequisites
- You need a Gemini account
- You need a Gemini API key. Apply here: https://aistudio.google.com/app/apikey
- Now install the Gemini API
pip install -q -U google-generativeai
How to use it
- Save the script below in the folder of your choice.
- Edit the script and insert your API key
- Create an chat.csv file, which contains the prompts in the first column to be sent to Gemini
- The output is saved as chatoutput.csv
import pathlib
import textwrap
import csv
import time
import google.generativeai as genai
# THIS PRODUCES LINKED CONVERSATIONAL CHATS
# !!! CAUTION: Hardcoding API keys is highly discouraged !!!
api_key = "YOUR-API-KEY"
genai.configure(api_key=api_key)
model = genai.GenerativeModel('gemini-pro')
chat = model.start_chat(history=[])
chat
# Rate limiting (adjust sleep time if needed)
RATE_LIMIT_SLEEP_SECONDS = 5
def process_query(query):
"""Sends a query to Gemini and handles potential rate limiting"""
try:
response = chat.send_message(query)
return response.text
except genai.exceptions.RateLimitExceededError as e:
print(f"Rate limit exceeded. Waiting {RATE_LIMIT_SLEEP_SECONDS} seconds...")
time.sleep(RATE_LIMIT_SLEEP_SECONDS)
return process_query(query) # Retry the query
# Load queries from input.csv
input_filepath = pathlib.Path("chat.csv")
with input_filepath.open('r', newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
queries = list(reader)
# Process queries and save responses
output_filepath = pathlib.Path("chatoutput.csv")
with output_filepath.open('w', newline='', encoding='utf-8') 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")