Google AI Generative Language API Client Library

0.11.0 · active · verified Sun Apr 05

The `google-ai-generativelanguage` library is the low-level Python client for the Google Generative Language API. It provides programmatic access to Google's generative AI models, such as Gemini, allowing developers to perform tasks like text generation, multimodal content understanding, and more. Maintained by Google, it is currently at version 0.11.0 and is compatible with Python 3.9 and newer. While functional for direct API interaction, for a higher-level and more unified experience with Gemini models, the `google-genai` library is often recommended.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate the `GenerativeServiceClient` and use it to generate text with the Gemini Pro model. It highlights the typical setup for authentication using Application Default Credentials (ADC), suitable for Google Cloud environments.

import os
from google.ai import generativelanguage_v1beta as glm

# Initialize the client. This client will attempt to ascertain credentials 
# from the environment, e.g., via Application Default Credentials (ADC).
# For local development, consider `gcloud auth application-default login`.
# For API Key-based authentication (e.g., from Google AI Studio), the `google-genai` 
# library (pip install google-genai) is generally recommended.
client = glm.GenerativeServiceClient()

model_name = "models/gemini-pro"  # Or another supported model like "models/text-bison-001"

# Prepare the content for generation
content = glm.Content(
    parts=[glm.Part(text="Write a short poem about a cat sitting by a window.")]
)

try:
    # Make the generate content request
    response = client.generate_content(model=model_name, contents=[content])

    # Extract the generated text
    if response.candidates:
        print(response.candidates[0].content.parts[0].text)
    else:
        print("No content generated.")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Ensure you have enabled the Generative Language API in your Google Cloud project and set up authentication.")

# It's good practice to explicitly close the client when done to release resources.
client.close()

view raw JSON →