Gemini API Quickstart

repository·main·Indexed 19 days ago

https://github.com/google-gemini/gemini-api-quickstart

A Python Flask application demonstrating the multi-modal capabilities of the Google AI Gemini API. It includes guides for setting up the environment, using the Google Gen AI SDK to send basic requests, managing chat sessions with gemini-2.0-flash, uploading images for multimodal chat, and streaming responses via Server-Sent Events (SSE).

Tokens
1.4K
Snippets
6
Records
6
Agent score
17%

What's inside gemini-api-quickstart

  1. Set up the Gemini API Quickstart Python environment

    main

    Follow these steps to prepare your local development environment for the Gemini API Quickstart application:

    1. Install Python: Ensure Python is installed from Python.org.
    2. Clone the repository: Clone this repository to your local machine.
    3. Create and activate a virtual environment:
      • macOS/Linux:
        python -m venv venv
        source venv/bin/activate
      • Windows:
        python -m venv venv
        .\venv\Scripts\activate
    4. Install dependencies: Run pip install -r requirements.txt to install the necessary Python packages.
    5. Configure Environment Variables:
      • Copy the example environment file: cp .env.example .env.
      • Open the .env file and add your Gemini API key.
    6. Run the Flask application: Execute flask run to start the server.

    The app will be accessible at http://localhost:5000.

    $ python -m venv venv
    $ source venv/bin/activate
    $ pip install -r requirements.txt
    $ cp .env.example .env
    $ flask run
  2. Initialize the Gemini API Client

    main

    To use the Gemini API within this application, initialize a genai.Client using an API key retrieved from your environment variables (typically stored in a .env file). A chat_session is created using client.chats.create() to maintain conversation state across multiple requests.

    import os
    from dotenv import load_dotenv
    from google import genai
    
    load_dotenv()
    
    client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
    chat_session = client.chats.create(model="gemini-2.0-flash")
  3. Send a basic request using the Google Gen AI SDK

    main

    To interact with the Gemini API using the Google Gen AI SDK, you can initialize a client, create a chat session, and send messages. The chat session maintains history, which can be retrieved using get_history().

    Key steps:

    1. Initialize genai.Client with your api_key.
    2. Create a chat session using client.chats.create(model="...").
    3. Use chat.send_message(text) to send prompts and receive responses.
    4. Iterate through chat.get_history() to inspect the conversation roles and content.
    from google import genai
    
    client = genai.Client(api_key="GEMINI_API_KEY")
    chat = client.chats.create(model="gemini-2.0-flash")
    
    # Send a message
    response = chat.send_message("Hello world!")
    print(response.text)
    
    # Send a follow-up message
    response = chat.send_message("Explain to me how AI works")
    print(response.text)
    
    # Inspect chat history
    for message in chat.get_history():
        print(f'role - {message.role}', end=": ")
        print(message.parts[0].text)
  4. Upload images for multimodal chat

    main

    The application supports uploading images with .png, .jpg, or .jpeg extensions. Files are processed via the /upload POST endpoint. The file is read into a BytesIO object and converted into a PIL Image object, which is then stored in a global next_image variable to be used in the subsequent chat request.

    # Endpoint: POST /upload
    # Supported extensions: {'png', 'jpg', 'jpeg'}
    
    # Internal logic for processing:
    file_stream = io.BytesIO(file.read())
    file_stream.seek(0)
    next_image = Image.open(file_stream)
  5. Send chat messages and stream responses

    main

    The application uses a two-step process for chatting:

    1. Send Message: A POST request to /chat with a JSON body containing {"message": "your text"} sets the next_message variable.
    2. Stream Response: A GET request to /stream triggers the Gemini API. If an image was previously uploaded, the request is sent as a multimodal list [next_message, next_image]. Otherwise, it sends only next_message. The response is streamed back to the client using Server-Sent Events (SSE) with the text/event-stream mimetype.
    # 1. Prepare the message (POST /chat)
    # Payload: {"message": "Hello Gemini"}
    
    # 2. Get the stream (GET /stream)
    # The server yields chunks in the format:
    # data: <chunk_text>
    #
    #
    # Internal API call:
    # response = chat_session.send_message_stream([next_message, next_image])