google.generativeai.GenerativeModel

The genai.GenerativeModel class wraps default parameters for calls to GenerativeModel.generate_message, GenerativeModel.count_tokens, and GenerativeModel.start_chat.

This family of functionality is designed to support multi-turn conversations, and multimodal requests. What media-types are supported for input and output is model-dependant.

import google.generativeai as genai
import PIL.Image
genai.configure(api_key='YOUR_API_KEY')
model = genai.GenerativeModel('models/gemini-pro')
result = model.generate_content('Tell me a story about a magic backpack')
response.text
"In the quaint little town of Lakeside, there lived a young girl named Lily..."

Multimodal input:

model = genai.GenerativeModel('models/gemini-pro')
result = model.generate_content([
    "Give me a recipe for these:", PIL.Image.open('scones.jpeg')])
response.text
"**Blueberry Scones** ..."

Multi-turn conversation:

chat = model.start_chat()
response = chat.send_message("Hi, I have some questions for you.")
response.text
"Sure, I'll do my best to answer your questions..."

To list the compatible model names use:

for m in genai.list_models():
    if 'generateContent' in m.supported_generation_methods:
        print(m.name)

model_name The name of the model to query. To list compatible models use
safety_settings Sets the default safety filters. This controls which content is blocked by the api before being returned.
generation_config A genai.GenerationConfig setting the default generation parameters to use.

model_name

Methods

count_tokens

View source

count_tokens_async

View source

generate_content

View source

A multipurpose function to generate responses from the model.

This GenerativeModel.generate_content method can handle multimodal input, and multiturn conversations.

model = genai.GenerativeModel('models/gemini-pro')
result = model.generate_content('Tell me a story about a magic backpack')
response.text

Streaming

This method supports streaming with the stream=True. The result has the same type as the non streaming case, but you can iterate over the response chunks as they become available:

result = model.generate_content('Tell me a story about a magic backpack', stream=True)
for chunk in response:
  print(chunk.text)

Multi-turn

This method supports multi-turn chats but is stateless: the entire conversation history needs to be sent with each request. This takes some manual management but gives you complete control:

messages = [{'role':'user', 'parts': ['hello']}]
response = model.generate_content(messages) # "Hello, how can I help"
messages.append(response.candidates[0].content)
messages.append({'role':'user', 'parts': ['How does quantum physics work?']})
response = model.generate_content(messages)

For a simpler multi-turn interface see GenerativeModel.start_chat.

Input type flexibility

While the underlying API strictly expects a list[glm.Content] objects, this method will convert the user input into the correct type. The hierarchy of types that can be converted is below. Any of these objects can be passed as an equivalent dict.

  • Iterable[glm.Content]
  • glm.Content
  • Iterable[glm.Part]
  • glm.Part
  • str, Image, or glm.Blob

In an Iterable[glm.Content] each content is a separate message. But note that an Iterable[glm.Part] is taken as the parts of a single message.

Arguments
contents The contents serving as the model's prompt.
generation_config Overrides for the model's generation config.
safety_settings Overrides for the model's safety settings.
stream If True, yield response chunks as they are generated.

generate_content_async

View source

The async version of Model.generate_content.

start_chat

View source