How to Use Gemini API in Python

Deepanshu Bhalla Add Comment , ,
Integrating Gemini API with Python

In this tutorial, you will learn how to use Google's Gemini AI model through its API in Python.

Update (February 05, 2025) : The tutorial has been updated for the latest Gemini model - Gemini 2.0 Flash which is twice as fast as the previous version. It supports real-time search and multimodal generation.
Steps to Access Gemini API

Follow the steps below to access the Gemini API and then use it in python.

  1. Visit Google AI Studio website.
  2. Sign in using your Google account.
  3. Create an API key.
  4. Install the Google AI Python library for the Gemini API using the command below :
    pip install google-genai
    .
Getting Started

The program below shows the easiest way to generate response of your question using generate_content() method. Please make sure to enter your API key in this section of code - ENTER_YOUR_API_KEY.

Python Code

from google import genai
from google.genai import types
import os
os.environ["API_KEY"] = 'ENTER_YOUR_API_KEY'

client = genai.Client(api_key=os.environ["API_KEY"])
response = client.models.generate_content(
    model='gemini-2.0-flash',
    contents='what does pandas package do?'
)
print(response.text)
Output
Pandas is a crucial tool for anyone working with data in Python. It simplifies data manipulation, cleaning, analysis, and visualization, making it an essential part of the data science workflow.
How to Fine Tune Model

You can set parameters of the model in the config argument of the function.

The temperature paramater is used to control the randomness in the responses the model generates. It lies between 0 and 2. The default value for Gemini-1.5-pro is 1.0. Lower temperature means lower randomness and more predictable output. Higher temperature closer to 2 means more randomness and the responses to be more creative.

Python Code


client = genai.Client(api_key=os.environ["API_KEY"])
response = client.models.generate_content(
    model='gemini-2.0-flash',
    contents='translate hello in spanish?',
    config=types.GenerateContentConfig(
            temperature = 1,
            top_p = 0.99,
            top_k = 0,
            max_output_tokens = 4096
            ),
)
print(response.text)
Output
The most common translation of "hello" in Spanish is **"Hola"**.
Chat using Gemini API

Often we need to converse by asking questions based on the response to the previous question. This functionality is similar to how chat works on Gemini website.

Python Code

client = genai.Client(api_key=os.environ["API_KEY"])
chat = client.chats.create(model='gemini-2.0-flash')

response = chat.send_message("2+2")
print(response.text)
# Output
# 2 + 2 = 4

response = chat.send_message("square of it")
print(response.text)
# Output
# The square of 4 is 16

response = chat.send_message("Add 4 to it")
print(response.text)
# Output
# Adding 4 to 16 gives us 20.
Google Search using Gemini API

You can fetch real-time information from google search using the Gemini API. It will help you in building smart tools that require latest information.

Python Code

from google import genai

client = genai.Client(api_key=os.environ["API_KEY"])
MODEL = 'gemini-2.0-flash'
search_tool = {'google_search': {}}

chat = client.chats.create(model=MODEL, config={'tools': [search_tool]})
r = chat.send_message('Current GDP of USA Quarterly')
response = r.candidates[0].content.parts[0].text
print(response)
How to Use Image in Your Prompt

You can use an image in your prompt (question). Refer the code below.

Using Image in Prompt in Gemini API
Source of this image : Wikipedia

To install the libraries for handling images using pip, you can run :
pip install requests pillow

Python Code
from google import genai
import requests
import PIL.Image
from io import BytesIO

url = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCGchJj9jVRP0jMND1a6tJXj7RcYWtnCO4J6YcbPTXrNxiCvs_3NSk7h2gB0h2sc_6bTvwPrBeBHwUA45AXAhaw1uuINuPDcHCbARxpgJIXM5Spi_0P45aR6tqZ_yof-YlNn41LhzHjfW-wsV3mhxBug4To8xtgyMzsHLbm3XoaHZmYUdNY1YWJA5rh6cB/s1600/Soccer-1490541_960_720.jpg"
response = requests.get(url)
img = PIL.Image.open(BytesIO(response.content))

client = genai.Client(api_key=os.environ["API_KEY"])
prompt = """What's inside the image."""

response = client.models.generate_content(
    model='gemini-2.0-flash',
    contents=[prompt, img]
)
print(response.text)
Output
The image shows a soccer game at night. Two players, one in white and one in green, are playing the ball. The player in white is kicking the ball past the player in green.

To use images from your local device, you can specify the file path of your image directly.

img = PIL.Image.open("C:\\Users\\deepa\\Downloads\\Soccer.jpg")
How to Set Instructions

By setting instructions, you can tell the AI model to always remember the important instructions while generating a response. You can set instructions in the system_instruction argument in the GenerativeModel( ) function.

Python Code

# System Instruction
instruction = """You are a linguistic expert who specializes in the English language.
I will give you text to check grammar of the sentence. Provide corrected sentence."""

client = genai.Client(api_key=os.environ["API_KEY"])
response = client.models.generate_content(
    model='gemini-2.0-flash',
    contents='Hello how is you?',
    config=types.GenerateContentConfig(
        system_instruction = instruction
            ),
)
print(response.text)
Output
The correct sentence is: "Hello, how are you?"
Question Answering

Let's say you have a large text and you want to build a chatbot where users can ask questions about the text and the chatbot will answer them.

Python Code

client = genai.Client(api_key=os.environ["API_KEY"])
def make_prompt(query, passage):
    escaped = passage.replace("\n", " ").replace("'", "").replace('"', "")
    prompt = (
        f"You are a helpful and informative bot that answers questions using text from the reference passage included below. "
        f"Be sure to respond in a complete sentence, being comprehensive, including all relevant background information. "
        f"However, you are talking to a non-technical audience, so be sure to break down complicated concepts and "
        f"strike a friendly and conversational tone. "
        f"If the passage is irrelevant to the answer, you may ignore it.\n"
        f"QUESTION: '{query}'\n"
        f"PASSAGE: '{escaped}'\n\n"
        f"ANSWER:\n"
    )
    return prompt

passage = "Title: Google to show AI generated results in search result\n Author: Mr. AI\nFull article:\n It is going to impact publishers significantly. It's estimated their traffic would go down by 25%."
query = "Who is the author of this article?"
prompt = make_prompt(query, passage)

response = client.models.generate_content(
    model='gemini-2.0-flash',
    contents=prompt
)

print(response.text)
Output
The author of the article "Google to show AI generated results in search result" is Mr. AI.
Text Embeddings

We can generate embeddings for text to help us find the right documents when we have questions about a certain topic. For example, if we have three documents about AI, we can use the embeddings to find the most relevant document related to our question.

Python Code

def embedding(prompt, model_name="text-embedding-004"): 
    response = client.models.embed_content(
    model=model_name,
    contents=prompt,
    )

    return response.embeddings

# Sample documents
documents = [
    "AI is like a smart helper in healthcare. It can find problems early by looking at lots of information, help doctors make plans just for you, and even make new medicines faster.",
    "AI needs to be open and fair. Sometimes, it can learn things that aren't right. We need to be careful and make sure it's fair for everyone. If AI makes a mistake, someone needs to take responsibility.",
    "AI is making school exciting. It can make learning fit you better, help teachers make fun lessons, and show when you need more help."
]

# Embed documents and query
embeddings = embedding(documents)
query_embedding = embedding("AI can generate misleading results many times.")
query_vector = query_embedding[0].values

dot_products = [
    sum(a * b for a, b in zip(doc_embedding.values, query_vector))
    for doc_embedding in embeddings
]

most_relevant_idx = dot_products.index(max(dot_products))
print(documents[most_relevant_idx])
Output
AI needs to be open and fair. Sometimes, it can learn things that aren't right. We need to be careful and make sure it's fair for everyone. If AI makes a mistake, someone needs to take responsibility.
List of Models

To see the list of latest models Gemini API supports, you can run the code below.

Python Code

for model in client.models.list(config={'page_size': 10, 'query_base': True}):
    print(model)
Output
models/chat-bison-001
models/text-bison-001
models/embedding-gecko-001
models/gemini-1.0-pro-latest
models/gemini-1.0-pro
models/gemini-pro
models/gemini-1.0-pro-001
models/gemini-1.0-pro-vision-latest
models/gemini-pro-vision
models/gemini-1.5-pro-latest
models/gemini-1.5-pro-001
models/gemini-1.5-pro-002
models/gemini-1.5-pro
models/gemini-1.5-flash-latest
models/gemini-1.5-flash-001
models/gemini-1.5-flash-001-tuning
models/gemini-1.5-flash
models/gemini-1.5-flash-002
models/gemini-1.5-flash-8b
models/gemini-1.5-flash-8b-001
models/gemini-1.5-flash-8b-latest
models/gemini-1.5-flash-8b-exp-0827
models/gemini-1.5-flash-8b-exp-0924
models/gemini-2.0-flash-exp
models/gemini-2.0-flash
models/gemini-2.0-flash-001
models/gemini-2.0-flash-lite-preview
models/gemini-2.0-flash-lite-preview-02-05
models/gemini-2.0-pro-exp
models/gemini-2.0-pro-exp-02-05
models/gemini-exp-1206
models/gemini-2.0-flash-thinking-exp-01-21
models/gemini-2.0-flash-thinking-exp
models/gemini-2.0-flash-thinking-exp-1219
models/learnlm-1.5-pro-experimental
models/embedding-001
models/text-embedding-004
models/aqa
Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 0 Response to "How to Use Gemini API in Python"
Next → ← Prev