Google's Gemini API provides cutting-edge AI capabilities for developers. This tutorial covers:
# Install official SDK
pip install google-generativeai
import google.generativeai as genai
# Configure with your API key
genai.configure(api_key='YOUR_API_KEY')
model = genai.GenerativeModel('gemini-pro')
response = model.generate_content(
"Explain Newton's third law to a 5 year old"
)
print(response.text)
response = model.generate_content(
"Write a 500-word story about aliens",
stream=True
)
for chunk in response:
print(chunk.text, end='')
chat = model.start_chat(history=[])
response = chat.send_message("Hi! I'm learning Python")
print(response.text)
response = chat.send_message("What's the best way to start?")
print(response.text)
response = model.generate_content(
"Controversial topic question...",
safety_settings={
'HARM_CATEGORY_HARASSMENT': 'BLOCK_ONLY_HIGH',
'HARM_CATEGORY_DANGEROUS': 'BLOCK_MEDIUM_AND_ABOVE'
}
)
try:
response = model.generate_content("Invalid prompt")
print(response.text)
except genai.types.StopCandidateException as e:
print(f"Safety violation: {e}")
except genai.GoogleAPIError as e:
print(f"API error: {e}")
import time
def safe_generate(prompt):
try:
return model.generate_content(prompt)
except genai.RateLimitError:
time.sleep(60)
return safe_generate(prompt)
Explore advanced features:
Official documentation: Google AI Developers
Category: Gemini
Similar Articles