From Novice to User: First Steps with the Gemini API
2 min readJul 21, 2024
This guide demonstrates how to integrate Google’s Gemini API into your Python projects. We’ll begin with the essential first step: installing the Python SDK.
pip install google-generativeai
Confirm this by running the command
import google.generativeai as genai
Obtaining an API Key
- Visit https://aistudio.google.com/app/apikey
- Log in to your Google account if prompted.
- Look for the option to generate an API key.
- Click to create a new API key.
Generate and copy your API key, then set it in your Python environment.
import os
os.environ['GOOGLE_GEMINI_API_KEY'] = 'YOUR_API_KEY'
List all the models available
for model in list(genai.list_models()):
if 'generateContent' in model.supported_generation_methods:
print(model.name)
Output:
models/gemini-1.0-pro
models/gemini-1.0-pro-001
models/gemini-1.0-pro-latest
models/gemini-1.0-pro-vision-latest
models/gemini-1.5-flash
models/gemini-1.5-flash-001
models/gemini-1.5-flash-latest
models/gemini-1.5-pro
models/gemini-1.5-pro-001
models/gemini-1.5-pro-latest
models/gemini-pro
models/gemini-pro-vision
Using Gemini Flash to Generate a Joke
To test the API, we’ll use Gemini Flash to generate a simple joke:
model = genai.GenerativeModel(model_name='gemini-1.5-flash')
prompt = 'Tell me a joke'
response = model.generate_content(prompt)
print(response.text)
Output:
"Why don't scientists trust atoms? \n\nBecause they make up everything! \n"