How to Use Google Gemini API?
1. Install & Import Packages
!pip install google-generativeai
import google.generativeai as genai
2. Setup your API key
Before you can use the Gemini API, you must first obtain an API key. If you don’t already have one, create a key with one click in Google AI Studio.
Get an API key => https://makersuite.google.com/app/apikey
Create one .env file in same directory and put below content in file
GOOGLE_API_KEY = your_google_api_key_here
# here am loading my Google API key which is stored in .env file in same project directory.
import os
from dotenv import load_dotenv
load_dotenv()
GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
# you can even skip above code and directly use your google api key. but this is not recommended way
# GOOGLE_API_KEY = <your _ggole_api_key_here>
genai.configure(api_key = GOOGLE_API_KEY)
3. Select Model
for m in genai.list_models():
if 'generateContent' in m.supported_generation_methods:
print(m.name)
Output: models/gemini-pro models/gemini-pro-vision
model = genai.GenerativeModel('gemini-pro')
4. Generate Response
response = model.generate_content("How Dog is different from cat?") Output:
<google.generativeai.types.generation_types.GenerateContentResponse at 0x23a497fdb70>
print(response.text)
Output:
‘1. Physical Characteristics:\n – Size: Dogs generally range in size from small to large, while cats tend to be smaller in size.\n – Fur: Dogs have fur, which can be short, long, or curly, while cats have fur that is typically shorter and smoother.\n – Ears: Dogs typically have floppy ears that hang down, while cats have pointed ears that stand upright.\n – Tail: Dogs have tails that are long and can wag, while cats have tails that are shorter and can twitch or swish.\n\n2. Temperament and Behavior:\n – Socialization: Dogs are generally more social animals and tend to enjoy the company of humans and other dogs. Cats, on the other hand, can be more independent and may prefer solitary activities.\n – Activity Level: Dogs are generally more active and energetic compared to cats. They require regular exercise and playtime. Cats, on the other hand, are often content to lounge around and may not require as much physical activity.\n – Affection: Dogs are often more affectionate and demonstrative in their affection towards humans. Cats can also be affectionate, but they may be more subtle in their expressions of love.\n\n3. Communication and Vocalization:\n – Vocalization: Dogs bark, howl, and whine to communicate with humans and other dogs. Cats meow, purr, and hiss to communicate with humans and other cats.\n – Body Language: Dogs use body language such as ear position, tail wagging, and facial expressions to communicate their emotions and intentions. Cats also use body language, such as tail position, dilated pupils, and arched backs, to convey their feelings.\n\n4. Care and Maintenance:\n – Grooming: Dogs require regular grooming, including brushing, bathing, and nail trimming. Cats are generally low-maintenance in terms of grooming and can typically manage their own hygiene.\n – Diet: Dogs are omnivores and can eat a variety of foods, including meat, vegetables, and grains. Cats are obligate carnivores and require a diet that is high in protein and low in carbohydrates.\n – Training: Dogs are generally easier to train than cats. They are more responsive to commands and can learn a variety of tricks and behaviors. Cats can be trained, but they may be more stubborn and independent.\n\n5. Lifespan:\n – Dogs: The average lifespan of a dog is 10-13 years, although some breeds may have shorter or longer lifespans.\n – Cats: The average lifespan of a cat is 12-18 years, although some breeds may have shorter or longer lifespans.’
5. Print Response
import textwrap
from IPython.display import Markdown
def to_markdown(text):
text = text.replace('•', ' *')
return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))
to_markdown(response.text)
6. Stream Response
response = model.generate_content("How Dog is different from cat?", stream = True)
for chunk in response:
print(chunk.text) Output: 1. **Size and Build:** Dogs come in a wide range of sizes, from petite Chihuahuas to imposing Great Danes. Cats, on the other hand, are typically smaller and more compact, with long, slender bodies. Their sleek build allows them to navigate tight spaces and jump high. 2. **Facial Features:** One of the most noticeable differences between dogs and cats is their facial structure. Dogs have a longer snout, a broader muzzle, and their eyes are typically located on the front of their head. This arrangement allows them to have a wider field of vision and assists in hunting and scavenging. Cats, on the other hand, have shorter snouts, smaller muzzles, and their eyes are placed more on the sides of their heads. This arrangement provides them with a wider angle of view, allowing them to detect movement better. 3. **Ears:** Another distinguishing feature between dogs and cats is their ears. Dogs have floppy ears that can be various shapes and sizes. Some breeds have pointed ears, while others have drop ears that hang down. Cats, on the other hand, have erect ears that are triangular in shape. Their ears are very sensitive and can swivel independently , helping them detect sounds from all directions. 4. **Tail:** Dogs and cats have different tail structures and uses. Dogs typically have long, flexible tails that they use for communication and balance. They wag their tails when they're happy, tuck them between their legs when they're scared, and hold them high when they're alert. Cats have shorter, more muscular tails that they use for balance, communication, and expressing emotions. They often flick or swish their tails to convey their mood. 5. **Fur:** Dogs and cats have different fur types. Dogs have a wide variety of fur textures and lengths, from short and smooth to long and curly. Cats, on the other hand, typically have shorter, softer fur that is easy to groom. Some breeds of cats have thicker, longer fur, while others have very short, plush coats. 6. **Temperament and Behavior:** Dogs and cats have different temperaments and behaviors. Dogs are generally more outgoing and social, seeking companionship and interaction with humans and other animals. They are often eager to please and respond well to training. Cats, on the other hand, are often more independent and aloof, preferring to observe and assess situations before engaging. They are also more territorial and can be less social with other animals, especially other cats. 7. **Diet and Nutritional Needs:** Dogs and cats have different nutritional requirements. Dogs are omnivores, meaning they can eat both plant-based and meat-based foods. They require a diet high in protein, carbohydrates, fats, and vitamins. Cats, on the other hand, are obligate carnivores, meaning they require animal-based protein for survival. Their diet should primarily consist of meat, with small amounts of carbohydrates and vegetables.
response.candidates
Output:
[index: 0content {
parts {
text: “1. **Size and Build:** Dogs come in a wide range of sizes, from petite Chihuahuas to imposing Great Danes. Cats, on the other hand, are typically smaller and more compact, with long, slender bodies. Their sleek build allows them to navigate tight spaces and jump high.\n\n2. **Facial Features:** One of the most noticeable differences between dogs and cats is their facial structure. Dogs have a longer snout, a broader muzzle, and their eyes are typically located on the front of their head. This arrangement allows them to have a wider field of vision and assists in hunting and scavenging. Cats, on the other hand, have shorter snouts, smaller muzzles, and their eyes are placed more on the sides of their heads. This arrangement provides them with a wider angle of view, allowing them to detect movement better.\n\n3. **Ears:** Another distinguishing feature between dogs and cats is their ears. Dogs have floppy ears that can be various shapes and sizes. Some breeds have pointed ears, while others have drop ears that hang down. Cats, on the other hand, have erect ears that are triangular in shape. Their ears are very sensitive and can swivel independently, helping them detect sounds from all directions.\n\n4. **Tail:** Dogs and cats have different tail structures and uses. Dogs typically have long, flexible tails that they use for communication and balance. They wag their tails when they\’re happy, tuck them between their legs when they\’re scared, and hold them high when they\’re alert. Cats have shorter, more muscular tails that they use for balance, communication, and expressing emotions. They often flick or swish their tails to convey their mood.\n\n5. **Fur:** Dogs and cats have different fur types. Dogs have a wide variety of fur textures and lengths, from short and smooth to long and curly. Cats, on the other hand, typically have shorter, softer fur that is easy to groom. Some breeds of cats have thicker, longer fur, while others have very short, plush coats.\n\n6. **Temperament and Behavior:** Dogs and cats have different temperaments and behaviors. Dogs are generally more outgoing and social, seeking companionship and interaction with humans and other animals. They are often eager to please and respond well to training. Cats, on the other hand, are often more independent and aloof, preferring to observe and assess situations before engaging. They are also more territorial and can be less social with other animals, especially other cats.\n\n7. **Diet and Nutritional Needs:** Dogs and cats have different nutritional requirements. Dogs are omnivores, meaning they can eat both plant-based and meat-based foods. They require a diet high in protein, carbohydrates, fats, and vitamins. Cats, on the other hand, are obligate carnivores, meaning they require animal-based protein for survival. Their diet should primarily consist of meat, with small amounts of carbohydrates and vegetables.”
}
role: “model”
}
finish_reason: STOP
safety_ratings {
category: HARM_CATEGORY_SEXUALLY_EXPLICIT
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_HATE_SPEECH
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_HARASSMENT
probability: NEGLIGIBLE
}
safety_ratings {
category: HARM_CATEGORY_DANGEROUS_CONTENT
probability: NEGLIGIBLE
}
citation_metadata {
}
]
7. Using Vision Model
Have some sample image. here am having img.png in same directory which I am using for inference.
import PIL.Image
img = PIL.Image.open("img.png")
model_vision = genai.GenerativeModel('gemini-pro-vision')
response = model_vision.generate_content(img)
to_markdown(response.text)
Output:
<IPython.core.display.Markdown object>
response = model_vision.generate_content(["write story around this image", img])
to_markdown(response.text)
Output:
<IPython.core.display.Markdown object>