I believe your goal is as follows.

  • You want to convert your top script with google-generativeai.

In this case, how about the following modification?

Modified script:

import google.generativeai as genai
import google.ai.generativelanguage as glm

apiKey = "###" # Please set your API key.

genai.configure(api_key=apiKey)

tool = glm.Tool(
    function_declarations=[
        glm.FunctionDeclaration(
            name="find_movies",
            description="find movie titles currently playing in theaters based on any description, genre, title words, etc.",
            parameters=glm.Schema(
                type=glm.Type.OBJECT,
                properties={
                    "location": glm.Schema(
                        type=glm.Type.STRING,
                        description="The city and state, e.g. San Francisco, CA or a zip code e.g. 95616",
                    ),
                    "description": glm.Schema(
                        type=glm.Type.STRING,
                        description="Any kind of description including category or genre, title words, attributes, etc.",
                    ),
                },
                required=["description"],
            ),
        ),
        glm.FunctionDeclaration(
            name="find_theaters",
            description="find theaters based on location and optionally movie title which is currently playing in theaters",
            parameters=glm.Schema(
                type=glm.Type.OBJECT,
                properties={
                    "location": glm.Schema(
                        type=glm.Type.STRING,
                        description="The city and state, e.g. San Francisco, CA or a zip code e.g. 95616",
                    ),
                    "movie": glm.Schema(
                        type=glm.Type.STRING,
                        description="Any movie title",
                    ),
                },
                required=["location"],
            ),
        ),
        glm.FunctionDeclaration(
            name="get_showtimes",
            description="Find the start times for movies playing in a specific theater",
            parameters=glm.Schema(
                type=glm.Type.OBJECT,
                properties={
                    "location": glm.Schema(
                        type=glm.Type.STRING,
                        description="The city and state, e.g. San Francisco, CA or a zip code e.g. 95616",
                    ),
                    "movie": glm.Schema(
                        type=glm.Type.STRING,
                        description="Any movie title",
                    ),
                    "theater": glm.Schema(
                        type=glm.Type.STRING,
                        description="Name of the theater",
                    ),
                    "date": glm.Schema(
                        type=glm.Type.STRING,
                        description="Date for requested showtime",
                    ),
                },
                required=["location", "movie", "theater", "date"],
            ),
        ),
    ]
)
model = genai.GenerativeModel("gemini-pro", tools=[tool])
messages = [
    glm.Part(text="Which theaters in Mountain View show Barbie movie?"),
    glm.Part(
        function_call=glm.FunctionCall(
            name="find_theaters",
            args={"location": "Mountain View, CA", "movie": "Barbie"},
        )
    ),
    glm.Part(
        function_response=glm.FunctionResponse(
            name="find_theaters",
            response={
                "name": "find_theaters",
                "content": {
                    "movie": "Barbie",
                    "theaters": [
                        {
                            "name": "AMC Mountain View 16",
                            "address": "2000 W El Camino Real, Mountain View, CA 94040",
                        },
                        {
                            "name": "Regal Edwards 14",
                            "address": "245 Castro St, Mountain View, CA 94040",
                        },
                    ],
                },
            },
        )
    ),
]
response = model.generate_content(messages)
print(response.text)

Testing:

When this script is run, the following result is obtained.

There are two theaters in Mountain View showing Barbie movie: AMC Mountain View 16 and Regal Edwards 14.
Answer from Tanaike on Stack Overflow
🌐
GitHub
googleapis.github.io › python-genai
Google Gen AI SDK documentation
from google.genai import types ... threshold='BLOCK_ONLY_HIGH', ) ] ), ) print(response.text) You can pass a Python function directly and it will be automatically called and responded by default....
🌐
GitHub
github.com › google-gemini › deprecated-generative-ai-python › blob › main › docs › api › google › generativeai › GenerativeModel.md
deprecated-generative-ai-python/docs/api/google/generativeai/GenerativeModel.md at main · google-gemini/deprecated-generative-ai-python
This GenerativeModel.generate_content method can handle multimodal input, and multi-turn conversations. >>> model = genai.GenerativeModel('models/gemini-1.5-flash') >>> response = model.generate_content('Tell me a story about a magic backpack') ...
Author   google-gemini
Discussions

Google gemini generate_content is not working in python API using function calling function_response - Stack Overflow
But in Python is not working. The gemini docs: https://ai.google.dev/gemini-api/docs/function-calling?hl=pt-br#multi-turn-example-1 ... import requests url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent" api_key = "YOUR_API_KEY" # Replace with your actual API key headers = { 'Content... More on stackoverflow.com
🌐 stackoverflow.com
How to set a timeout on Google Gemini generate content request with the Vertex AI SDK for Python - Stack Overflow
I am using Google's Vertex AI SDK for Python to access the Gemini Pro model and generate content. I would like to set a timeout (e.g., 30 seconds) for the generate content call to complete or raise... More on stackoverflow.com
🌐 stackoverflow.com
I want to `generate_content` through the Gemini API with Gemma models (but not instruction tuned) in python but I can't figure it out?
https://huggingface.co/google/gemma-3-12b-pt Use Hugging Face models and deploy on Amazon or Azure More on reddit.com
🌐 r/GoogleGeminiAI
3
2
August 9, 2025
python - How to Use Gemini API to Process and Extract Data from an Image? - Stack Overflow
I'm working on integrating Google's Gemini API into my project, where I need to analyze an image and extract meaningful data from it. However, I'm unsure about the proper way to send an image to Ge... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

Q3: What's the safest API Key management approach? How to handle different environments (dev/staging/prod)?
Three-stage security upgrade. (1) Absolutely don't do: (A) hardcode in code, (B) commit to git, (C) place in frontend JavaScript (visible to users), (D) paste in Slack / email. (2) Basic approach (personal / small projects): (A) .env file + .gitignore — GEMINIAPIKEY=xxx in .env, code uses os.getenv(); (B) use python-dotenv — from dotenv import loaddotenv; loaddotenv(). (3) Advanced approach (teams / production): (A) GCP Secret Manager — from google.cloud import secretmanager; client.accesssecretversion(...); (B) AWS Secrets Manager / Azure Key Vault — similar; (C) Environment variable injectio
🌐
cloudinsight.cc
cloudinsight.cc › home › blog › gemini api python tutorial: 2026 complete guide to calling google ai models from scratch
Gemini API Python Tutorial: 2026 Complete Guide to Calling Google ...
Q1: What's the difference between `google-generativeai` and `vertexai` SDKs? Which should I use?
Depends on which endpoint you're targeting. Gemini API now has two main Python SDKs: (1) google-generativeai (recommended for beginners) — calls Google AI Studio's API endpoint (generativelanguage.googleapis.com), needs only API key auth, best for personal / prototype development. Install: pip install google-generativeai; example: genai.GenerativeModel('gemini-2.0-flash').generate_content(...). (2) google-cloud-aiplatform (vertexai) — calls Vertex AI's endpoint, requires GCP account and Application Default Credentials, suits enterprise production. Install: pip install google-cloud-aiplatform;
🌐
cloudinsight.cc
cloudinsight.cc › home › blog › gemini api python tutorial: 2026 complete guide to calling google ai models from scratch
Gemini API Python Tutorial: 2026 Complete Guide to Calling Google ...
Q5: For long documents (100-page PDFs, 1-hour videos), can Gemini's context really handle it?
Yes, but watch cost and strategy. Gemini 2.0 Pro natively supports 2M token context, equivalent to approximately 1.5M Chinese characters / 800 pages / 2 hours of video. Real-world examples: (1) 100-page PDF processing: ~40,000 tokens, using genai.uploadfile('report.pdf') to upload, then reference in prompt. Cost: Flash ~$0.003, Pro ~$0.05 per query. (2) 1-hour video analysis: ~500,000 tokens (depending on resolution), genai.uploadfile('video.mp4'). Cost: Flash ~$0.04, Pro ~$0.6 per query. (3) Full text of 10 books: if each is 100K tokens, 10 books = 1M tokens, feasible to include all at once.
🌐
cloudinsight.cc
cloudinsight.cc › home › blog › gemini api python tutorial: 2026 complete guide to calling google ai models from scratch
Gemini API Python Tutorial: 2026 Complete Guide to Calling Google ...
🌐
GitHub
github.com › googleapis › python-genai
GitHub - googleapis/python-genai: Google Gen AI Python SDK provides an interface for developers to integrate Google's generative models into their Python applications. · GitHub
1 month ago - Args: location: The city and state, e.g. San Francisco, CA """ return 'sunny' response = client.models.generate_content( model='gemini-3.5-flash', contents='What is the weather like in Boston?', config=types.GenerateContentConfig(tools=[get_current_weather]), ) print(response.text) If you pass in a python function as a tool directly, and do not want automatic function calling, you can disable automatic function calling as follows:
Starred by 3.8K users
Forked by 929 users
Languages   Python
🌐
CloudInsight
cloudinsight.cc › home › blog › gemini api python tutorial: 2026 complete guide to calling google ai models from scratch
Gemini API Python Tutorial: 2026 Complete Guide to Calling Google AI Models from Scratch | CloudInsight - Cloud Cost Optimization Experts
March 21, 2026 - Gemini SDK supports streaming; combining with SSE (Server-Sent Events) to frontend is most common. Python implementation: response = model.generate_content(prompt, stream=True) → for chunk in response: print(chunk.text).
🌐
Medium
medium.com › @kobigan.k › getting-started-with-gemini-api-a-simple-text-generation-example-in-python-21a9a364298e
Getting Started with Gemini API: A Simple Text Generation Example in Python | by Kobigan Krishnananthan | Medium
February 2, 2026 - try: response = model.generate_content("what is whitenights book") print("\n--- Gemini 3 Response ---") print(response.text) except Exception as e: print(f"Error: {e}") ... This is a natural language prompt sent directly to the model. ... All of this happens in milliseconds. ... ✔ Secure API key handling ✔ Model initialization ✔ Prompt-based text generation ✔ Error handling ✔ Clean, readable Python code
🌐
Google AI
ai.google.dev › gemini api › getting started with gemini api
Getting started with Gemini API | Google AI for Developers
2 weeks ago - You must preserve and resend all model-generated steps (including thought and function_call steps) exactly as received. from google import genai client = genai.Client() history = [ { "type": "user_input", "content": [{"type": "text", "text": "I have 2 dogs in my house."}] } ] interaction1 = client.interactions.create( model="gemini-3.5-flash", store=False, input=history ) print("Response 1:", interaction1.steps[-1].content[0].text) for step in interaction1.steps: history.append(step.model_dump()) history.append({ "type": "user_input", "content": [{"type": "text", "text": "How many paws are in my house?"}] }) interaction2 = client.interactions.create( model="gemini-3.5-flash", store=False, input=history ) print("Response 2:", interaction2.steps[-1].content[0].text)
Find elsewhere
Top answer
1 of 1
1

I believe your goal is as follows.

  • You want to convert your top script with google-generativeai.

In this case, how about the following modification?

Modified script:

import google.generativeai as genai
import google.ai.generativelanguage as glm

apiKey = "###" # Please set your API key.

genai.configure(api_key=apiKey)

tool = glm.Tool(
    function_declarations=[
        glm.FunctionDeclaration(
            name="find_movies",
            description="find movie titles currently playing in theaters based on any description, genre, title words, etc.",
            parameters=glm.Schema(
                type=glm.Type.OBJECT,
                properties={
                    "location": glm.Schema(
                        type=glm.Type.STRING,
                        description="The city and state, e.g. San Francisco, CA or a zip code e.g. 95616",
                    ),
                    "description": glm.Schema(
                        type=glm.Type.STRING,
                        description="Any kind of description including category or genre, title words, attributes, etc.",
                    ),
                },
                required=["description"],
            ),
        ),
        glm.FunctionDeclaration(
            name="find_theaters",
            description="find theaters based on location and optionally movie title which is currently playing in theaters",
            parameters=glm.Schema(
                type=glm.Type.OBJECT,
                properties={
                    "location": glm.Schema(
                        type=glm.Type.STRING,
                        description="The city and state, e.g. San Francisco, CA or a zip code e.g. 95616",
                    ),
                    "movie": glm.Schema(
                        type=glm.Type.STRING,
                        description="Any movie title",
                    ),
                },
                required=["location"],
            ),
        ),
        glm.FunctionDeclaration(
            name="get_showtimes",
            description="Find the start times for movies playing in a specific theater",
            parameters=glm.Schema(
                type=glm.Type.OBJECT,
                properties={
                    "location": glm.Schema(
                        type=glm.Type.STRING,
                        description="The city and state, e.g. San Francisco, CA or a zip code e.g. 95616",
                    ),
                    "movie": glm.Schema(
                        type=glm.Type.STRING,
                        description="Any movie title",
                    ),
                    "theater": glm.Schema(
                        type=glm.Type.STRING,
                        description="Name of the theater",
                    ),
                    "date": glm.Schema(
                        type=glm.Type.STRING,
                        description="Date for requested showtime",
                    ),
                },
                required=["location", "movie", "theater", "date"],
            ),
        ),
    ]
)
model = genai.GenerativeModel("gemini-pro", tools=[tool])
messages = [
    glm.Part(text="Which theaters in Mountain View show Barbie movie?"),
    glm.Part(
        function_call=glm.FunctionCall(
            name="find_theaters",
            args={"location": "Mountain View, CA", "movie": "Barbie"},
        )
    ),
    glm.Part(
        function_response=glm.FunctionResponse(
            name="find_theaters",
            response={
                "name": "find_theaters",
                "content": {
                    "movie": "Barbie",
                    "theaters": [
                        {
                            "name": "AMC Mountain View 16",
                            "address": "2000 W El Camino Real, Mountain View, CA 94040",
                        },
                        {
                            "name": "Regal Edwards 14",
                            "address": "245 Castro St, Mountain View, CA 94040",
                        },
                    ],
                },
            },
        )
    ),
]
response = model.generate_content(messages)
print(response.text)

Testing:

When this script is run, the following result is obtained.

There are two theaters in Mountain View showing Barbie movie: AMC Mountain View 16 and Regal Edwards 14.
🌐
Medium
medium.com › @adarsh.ajay › unleashing-the-power-of-google-gemini-with-python-a-step-by-step-guide-ed5e2ea1818f
Unleashing the Power of Google Gemini with Python: A Step-by-Step Guide | by Adarsh Ajay | Medium
December 17, 2024 - Generative AI models have taken ... processing. In this guide, we’ll explore practical Python scripts for using Gemini models efficiently, from basic text generation to advanced multimedia tasks like extracting content from images, summarizing videos, and fine-tuning custom ...
🌐
GeeksforGeeks
geeksforgeeks.org › artificial intelligence › getting-started-with-google-gemini-with-python-api-integration-and-model-capabilities
Getting Started with Google Gemini with Python: API Integration and Model Capabilities - GeeksforGeeks
July 23, 2025 - 1. The GenerativeModel.generate_content API is designed to handle multimodal prompts and returns a text output. Upload any image on colab. 2. Use the gemini-1.5-flash model and pass the image to the model with generate_content.
🌐
Patloeber
patloeber.com › gemini-multimodal
Get started with Gemini's multimodal capabilities | Patrick Loeber
February 17, 2025 - To get started, install the google-genai Python SDK and obtain a free API key in AI Studio. pip install -U -q google-genai · Next, set up the client using the following code: from google import genai client = genai.Client(api_key='YOUR_GOO...
🌐
ListenData
listendata.com › home › gemini
How to Use Gemini API in Python
April 3, 2026 - The latest Gemini models do not support completely turning thinking off. However, setting thinking_level to minimal means the model is unlikely to perform reasoning, although some internal thinking may still occur. from google import genai from google.genai import types client = genai.Client() response = client.models.generate_content( model="gemini-flash-latest", contents="Solve equation of 2x+1=5", config=types.GenerateContentConfig( thinking_config=types.ThinkingConfig(thinking_level="minimal") ), ) print(response.text)
🌐
LiteLLM
docs.litellm.ai › supported endpoints › /generatecontent
/generateContent | liteLLM
from litellm.google_genai import generate_content_stream from google.genai.types import ContentDict, PartDict import os # Set API key os.environ["GEMINI_API_KEY"] = "your-gemini-api-key" contents = ContentDict( parts=[ PartDict(text="Write a long story about space exploration") ], role="user", ) response = generate_content_stream( contents=contents, model="gemini/gemini-2.0-flash", max_tokens=500, ) for chunk in response: print(chunk)
🌐
Reddit
reddit.com › r/googlegeminiai › i want to `generate_content` through the gemini api with gemma models (but not instruction tuned) in python but i can't figure it out?
r/GoogleGeminiAI on Reddit: I want to `generate_content` through the Gemini API with Gemma models (but not instruction tuned) in python but I can't figure it out?
August 9, 2025 -

I am working on a small RAG pipeline and while testing it, I was using `gemma3:4b` locally on my computer with ollama to generate responses, but this was not the fastest (though the quality of responses was good). So I thought I would try to use the free tier of the gemini API and get faster responses and maybe even be able to use the 12b model (so I thought). But I am unable to find any documentation on using these...

From playing around in AI Studio, I can see that I could use the `gemma-3-Xb-it` (i.e., instruction-tuned) models but the responses I am getting from these for my conversational RAG experience are much worse. Trying to replace the `-it` with `-pt` (pre-trained) simply threw an error that the model does not exist.

Would appreciate any help on trying to figure out if its even possible to use gemma models through the API (because although `gemini-2.X-flash-lite` works fine, I just somehow preferred the tone and responses of the gemma model even with the same system prompt etc.)
anyways, thanks!

🌐
Medium
medium.com › @b.antoine.se › unleash-the-power-of-google-gemini-a-comprehensive-python-script-for-ai-generation-0b0e608d840b
Unleash the Power of Google Gemini: A Comprehensive Python Script for AI Generation | by Bryan Antoine | Medium
October 21, 2024 - This article delves into a powerful and versatile Python script designed to harness the capabilities of Google’s Gemini AI. This script offers a comprehensive toolkit for developers, enabling them to effortlessly integrate Gemini into their projects and unlock a wide range of AI-powered features. ... Text Generation: Generate creative text from prompts, images, PDFs, and even audio files.
🌐
Google
docs.cloud.google.com › gemini enterprise agent platform › generate content with the gemini api
Generate content with the Gemini API | Gemini Enterprise Agent Platform | Google Cloud Documentation
Use generateContent or streamGenerateContent to generate content with Gemini. The Gemini model family includes models that work with multimodal prompt requests. The term multimodal indicates that you can use more than one modality, or type of ...
🌐
GitHub
googleapis.github.io › python-genai › genai.html
Submodules - Google Gen AI SDK documentation
Makes an API request to generate content using a model and yields the model’s response in chunks. For the model parameter, supported formats for Gemini Enterprise Agent Platform API include: - The Gemini model ID, for example: ‘gemini-2.0-flash’ - The full resource name starts with ...
🌐
Google AI
ai.google.dev › gemini api › generating content
Generating content | Gemini API | Google AI for Developers
May 20, 2026 - ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: os.Getenv("GEMINI_API_KEY"), Backend: genai.BackendGeminiAPI, }) if err != nil { log.Fatal(err) } contents := []*genai.Content{ genai.NewContentFromText("Write a story about a magic backpack.", genai.RoleUser), } response, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil) if err != nil { log.Fatal(err) } printResponse(response)
🌐
Codecademy
codecademy.com › article › how-to-build-ai-agents-with-gemini-3
How to Build AI Agents with Gemini 3 in 10 Minutes | Codecademy
Execute Python code to perform analysis but DO NOT show the code itself - only show the formatted results and insights. Use pandas for analysis and present all tables in clean DataFrame format. """ # Send request to Gemini · response = self.model.generate_content(prompt) # Print the results ·
Top answer
1 of 2
2

For Python, it is easier to work with the Python unified SDK than playing directly with the endpoints using libs like requests.

Using the Python SDK, you have two ways to send images within your prompts:

  1. you can send them inline, very straightforward:
image = Image.open(img_path)

response = client.models.generate_content(
    model=MODEL_ID,
    contents=[
        image,
        "ask something about the image here"
    ]
)

Or you can use the (File API)[https://googleapis.github.io/python-genai/genai.html#genai.files.AsyncFiles.upload] for payloads that may be higher than 20MB. Using that you will first upload the media using the SDK:

file_ref = client.files.upload(path=img_path)

And then you will reference the file API object file_ref within your prompt:

response = client.models.generate_content(
    model=MODEL_ID,
    contents=[
        file_ref,
        "ask something about the image here"
    ]
)

The response for your requests using those example requests will be text only and will can handle the results in the same way you do for text only prompts - like exploring the response object with structures like response.text for the model answer in text. more details about the response object structure can be found at the SDK reference doc.

This Gemini API get started notebook may be useful as well.

hope that helps.

2 of 2
0

i have built web tool for image editing and also mobile app you can test the web tool live here https://gemma-ai.vercel.app/

Gemini take image input as base64 and also its return image in base64 format

To perform image editing, add an image as input. The following example demonstrats uploading base64 encoded images

from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO

import PIL.Image

image = PIL.Image.open('/path/to/image.png')

client = genai.Client()

text_input = ('Hi, This is a picture of me.'
            'Can you add a llama next to me?',)

response = client.models.generate_content(
    model="gemini-2.0-flash-exp-image-generation",
    contents=[text_input, image],
    config=types.GenerateContentConfig(
      response_modalities=['Text', 'Image']
    )
)

for part in response.candidates[0].content.parts:
  if part.text is not None:
    print(part.text)
  elif part.inline_data is not None:
    image = Image.open(BytesIO(part.inline_data.data))
    image.show()

for more information you can visit :https://ai.google.dev/gemini-api/docs/image-generation#python