Getting started with Gemini api in Python
A simple tutorial on gemini api
Google has released Gemini-Pro and Gemini-Pro-Vision, typically available free of charge to programmers (no cost for up to 60 requests per minute), making it an excellent and cost-effective way to incorporate Large Language Models (LLMs) into your programs. So lets get started.
Initial setup
pip install -q -U google-generativeai
Gemini Pro (without memory)
Firstly, import the google-generativeai
library. Then, acquire your API key from the website ai.google.dev
. After obtaining the key, select the model you wish to use. Currently, there are two generative models available: gemini-pro
and gemini-pro-vision
. To generate content, use the .generate_content
method. Finally, to display the generated response, use the print
function, which will present the response in Markdown format.
import google.generative as genai
genai.configure(api_key="ENTER YOUR API KEY HERE")
model = genai.model("gemini-pro")
response = model.generate_content("Your input string")
print(response)
Gemini Pro (with memory from previous chat)
To continue a conversation using information from previous interactions, initiate a chat session with the model using the .start_chat
method. This method allows for an ongoing dialogue, where each new message takes into account the history of the conversation. You can send multiple messages using this method, and the model will respond accordingly, reflecting the context of the previous chat
chat = model.start_chat(history=[])
response = chat.send_message("My name is Riza whats your name")
print(response.text)
# Output:
# I am a large language model, trained by Google.
response = chat.send_message("What is my name?")
print(response.text)
# Your name is Riza.
Gemini-vision-pro
First to interact with the vision pro api we need to have Pillow. To install Pillow just pip install it
pip install pillow
then open the image using pillow
from PIL import Image
img = Image.open('image.png')
#The image named "image.png" is located in the script's folder.
img

Then, you can either send the image directly to the model or accompany it with text. To include it with text, simply pass a list containing both the text and the image as arguments to the `generate_content` method.
response = model.generate_content(img) # simply pass the image
print(response.text)
#Output:
# Stunning!
response = model.generate_content(["Describe the image", img])
# pass image and text
print(response.text)
#Output:
# This is an image of a white lion with blue eyes.
# The lion is wearing a golden crown and has a lot of jewelry on its body.
# The lion is sitting in front of a black background.
That’s all for now. Feel free to connect with me on LinkedIn and follow me on Medium, where I publish these types of articles often.