Text Generation with Google Gemini

Nov 14 2024 · Python 3.12, Google Gemini, JupyterLab, Visual Studio Code

Lesson 03: Text Generation with Google Gemini API

Demo: Text Generation with Gemini API

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Demo

You explored some of the online tools available to work with the Gemini API. Now you’ll learn how to use it in your own local environment. Gemini supports many languages, you’ll be using Python.

GOOGLE_API_KEY = "YOUR API KEY"
%pip install -U -q google-generativeai
%pip install python-dotenv
import google.generativeai as genai
import os
from dotenv import load_dotenv
0.6s
load_dotenv()
os.environ.get('GOOGLE_API_KEY')
genai.configure(api_key=os.environ.get('GOOGLE_API_KEY'))
for m in genai.list_models():
  if 'generateContent' in m.supported_generation_methods:
    print(m.name)
models/gemini-1.0-pro
models/gemini-pro
models/gemini-1.0-pro-001
models/gemini-1.0-pro-vision-latest
models/gemini-pro-vision
models/gemini-1.5-pro-latest
models/gemini-1.5-pro-001
models/gemini-1.5-pro
models/gemini-1.5-pro-exp-0801
models/gemini-1.5-pro-exp-0827
models/gemini-1.5-flash-latest
models/gemini-1.5-flash-001
models/gemini-1.5-flash-001-tuning
models/gemini-1.5-flash
models/gemini-1.5-flash-exp-0827
models/gemini-1.5-flash-8b-exp-0827
genai.get_model('models/gemini-pro-vision')
model = genai.GenerativeModel('gemini-pro')
response = model.generate_content(
  'What kind of safety features does Google Gemini API provide for
    prompts'
)
print(response)
print(response.text)
response = model.generate_content('List some prompts that are flagged
  as hate speech')
print(response)
print(response.text)
ValueError: Invalid operation: The `response.text` quick accessor requires
  the response to contain a
valid `Part`, but none were returned. Please check the
  `candidate.safety_ratings` to determine if
the response was blocked.
response = model.generate_content('All purple people eaters are homicidal
  maniacs!!!')
print(response)
from google.generativeai.types import HarmCategory, HarmBlockThreshold

safety = {
  HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold
    .BLOCK_ONLY_HIGH,
  HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold
    .BLOCK_ONLY_HIGH
}
response = model.generate_content(
  'All purple people eaters are homicidal maniacs!!!',
  safety_settings= safety
)

print(response)
See forum comments
Cinema mode Download course materials from Github
Previous: Text Generation with Gemini API Next: Text Generation Parameters