API usuage
March 29, 2024Less than 1 minute
Text
import pathlib
import textwrap
import google.generativeai as genai
from IPython.display import display
from IPython.display import Markdown
# Used to securely store your API key
from google.colab import userdata
def to_markdown(text):
text = text.replace('•', ' *')
return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))
# Or use `os.getenv('GOOGLE_API_KEY')` to fetch an environment variable.
GOOGLE_API_KEY=userdata.get('PaLM_Key')
genai.configure(api_key=GOOGLE_API_KEY)
for m in genai.list_models():
if 'generateContent' in m.supported_generation_methods:
print(m.name)
model = genai.GenerativeModel('gemini-pro')
response = model.generate_content("What is the meaning of life?")
Image
from PIL import Image
import io
import requests as req
img = Image.open(io.BytesIO(req.get('https://ai.google.dev/static/tutorials/python_quickstart_files/output_CjnS0vNTsVis_0.png').content))
model = genai.GenerativeModel('gemini-pro-vision')
response = model.generate_content(img)
to_markdown(response.text)
response = model.generate_content(["Write a short, engaging blog post based on this picture. It should include a description of the meal in the photo and talk about my journey meal prepping.", img], stream=True)
response.resolve()
to_markdown(response.text)
Chat conversation
model = genai.GenerativeModel('gemini-pro')
chat = model.start_chat(history=[])
chat
response = chat.send_message("In one sentence, explain how a computer works to a young child.")
to_markdown(response.text)
chat.history
response = chat.send_message("Okay, how about a more detailed explanation to a high schooler?", stream=True)
for chunk in response:
print(chunk.text)
print("_"*80)
for message in chat.history:
display(to_markdown(f'**{message.role}**: {message.parts[0].text}'))
model.count_tokens("What is the meaning of life?")
model.count_tokens(chat.history)