Gemini-API
A reverse-engineered asynchronous Python wrapper for the Google Gemini web app (formerly Bard).
Features
- Persistent Cookies - Automatically refreshes cookies in background. Optimized for always-on services.
- Image Generation - Natively supports generating and editing images with natural language.
- Video & Audio Generation - Supports generating videos and audio/music content natively.
- Deep Research - Full deep research workflow with plan creation, status polling, and result retrieval.
- System Prompt - Supports customizing the model's system prompt with Gemini Gems.
- Extension Support - Supports generating content with Gemini extensions, such as YouTube and Gmail.
- Classified Outputs - Categorizes text, thoughts, images, videos, and audio in the response.
- Streaming Mode - Supports stream generation, yielding partial outputs as they are generated.
- CLI Tool - Standalone command-line interface for quick interactions.
- Official Flavor - Provides a simple and elegant interface inspired by Google Generative AI's official API.
- Asynchronous - Utilizes
asyncioto run generation tasks and return outputs efficiently.
Table of Contents
- Features
- Table of Contents
- Installation
- Authentication
- Usage
- Initialization
- Generate Content
- Generate Content with Files
- Conversations Across Multiple Turns
- Continue Previous Conversations
- Read Conversation History
- Delete Previous Conversations from Gemini History
- Temporary Mode
- Streaming Mode
- Select Language Model
- List Available Models
- Apply System Prompt with Gemini Gems
- Manage Custom Gems
- Retrieve Model's Thought Process
- Retrieve Images in Response
- Generate and Edit Images
- Retrieve Videos and Audio
- Generate Content with Gemini Extensions
- Check and Switch to Other Reply Candidates
- Deep Research
- Logging Configuration
- CLI Tool
- References
- Stargazers
Installation
[!NOTE]
This package requires Python 3.11 or higher.
Install or update the package with pip.
pip install -U gemini_webapi
Optionally, the package offers a way to automatically import cookies from your local browser via optional dependency browser-cookie3. To enable this feature, install gemini_webapi[browser] instead. Currently, only Firefox is supported. The latest information about supported browsers can be found in the browser-cookie3 repository.
pip install -U gemini_webapi[browser]
Authentication
[!TIP]
If
browser-cookie3is installed, you can skip this step and go directly to the usage section. Just make sure you are logged in to in your browser.
- Go to and log in with your Google account
- Press F12 to open the web inspector, go to the
Networktab, and refresh the page - Click any request and copy the cookie values of
__Secure-1PSIDand__Secure-1PSIDTS
[!NOTE]
If your application is deployed in a containerized environment (e.g. Docker), you may want to persist the cookies with a volume to avoid re-authentication every time the container rebuilds. You can set
GEMINI_COOKIE_PATHenvironment variable to specify the path where auto-refreshed cookies are stored. Make sure the path is writable by the application.Here's part of a sample
docker-compose.ymlfile:
services:
main:
environment:
GEMINI_COOKIE_PATH: /tmp/gemini_webapi
volumes:
- ./gemini_cookies:/tmp/gemini_webapi
[!NOTE]
The API's auto-cookie-refreshing feature doesn't require
browser-cookie3and is enabled by default. It allows you to keep the API service running without worrying about cookie expiration.This feature may require you to log in to your Google account again in the browser. This is expected behavior and won't affect the API's functionality.
To avoid this, it's recommended to get cookies from a separate browser session and close it as soon as possible for best utilization (e.g. a fresh login in the browser's private mode). More details can be found in issue #6.
[!TIP]
If cookies expire frequently, use Firefox to extract cookies. Recent versions of Chromium-based browsers use "Device Bound Session Credentials", which improves security but causes cookies to remain valid for only a few hours and prevents them from being renewed.
Usage
Initialization
Import the required packages and initialize a client with your cookies from the previous step. After successful initialization, the API will automatically refresh __Secure-1PSIDTS in the background as long as the process is alive.
import asyncio
from gemini_webapi import GeminiClient
# Replace "COOKIE VALUE HERE" with your actual cookie values.
# Leave Secure_1PSIDTS empty if it's not available for your account.
Secure_1PSID = "COOKIE VALUE HERE"
Secure_1PSIDTS = "COOKIE VALUE HERE"
async def main():
# If browser-cookie3 is installed, simply use `client = GeminiClient()`
client = GeminiClient(Secure_1PSID, Secure_1PSIDTS, proxy=None)
await client.init(timeout=30, auto_close=False, close_delay=300, auto_refresh=True)
asyncio.run(main())
[!TIP]
auto_closeandclose_delayare optional arguments for automatically closing the client after a certain period of inactivity. This feature is disabled by default. In an always-on service like a chatbot, it's recommended to setauto_closetoTruewith a reasonableclose_delayvalue for better resource management.
Generate Content
Ask a single-turn question by calling GeminiClient.generate_content, which returns a gemini_webapi.ModelOutput object containing the generated text, images, thoughts, and conversation metadata.
async def main():
response = await client.generate_content("Hello World!")