Setting up
Get the API key from here: https://ai.google.dev/tutorials/setup
import google.generativeai as genai
import os
from IPython.display import Markdown, display
gemini_api_key = os.environ["GEMINI_API_KEY"]
genai.configure(api_key = gemini_api_key)
model = genai.GenerativeModel('gemini-pro')
Using Gemini Pro
response = model.generate_content("Who is the God of Universe?")
display(Markdown(response.text))
response.candidates
Code Generation using Gemini Pro
response = model.generate_content("Build a simple game in Javascript which could be run in browser when the script code run in console.")
display(Markdown(response.text))
Content generation using Gemini Pro
response = model.generate_content(
'Write a short story about first encounter with outer space.',
generation_config=genai.types.GenerationConfig(
candidate_count=1,
stop_sequences=['space'],
max_output_tokens=200,
temperature=0.7)
)
Markdown(response.text)
Streaming Response
model = genai.GenerativeModel('gemini-pro')
response = model.generate_content("Write a PySpark function for cleaning the data.", stream=True)
for chunk in response:
print(chunk.text)
Using Gemini Pro Vision (For Identifying Images metadata)
import PIL.Image
from IPython.display import display
img = PIL.Image.open('images/taj.jpg')
# Reduce the size of the image before displaying
img.thumbnail((800, 800))
display(img)
model = genai.GenerativeModel('gemini-pro-vision')
response = model.generate_content(img)
Markdown(response.text)
response = model.generate_content(["Write a travel blog post using the image as reference.", img])
Markdown(response.text)
Chat Conversations Session
model = genai.GenerativeModel('gemini-pro')
chat = model.start_chat(history=[])
chat.send_message("Can you please guide me on how to start playing Dota 2?")
chat.history
for message in chat.history:
display(Markdown(f'**{message.role}**: {message.parts[0].text}'))
chat.send_message("Which Dota 2 heroes should I start with?")
for message in chat.history:
display(Markdown(f'**{message.role}**: {message.parts[0].text}'))