Gemini-API
A reverse-engineered asynchronous python wrapper for 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 modifying images with natural language.
- Extension Support - Supports generating contents with Gemini extensions on, like YouTube and Gmail.
- Classified Outputs - Automatically categorizes texts, web images and AI generated images in the response.
- Official Flavor - Provides a simple and elegant interface inspired by Google Generative AI's official API.
- Asynchronous - Utilizes
asyncioto run generating tasks and return outputs efficiently.
Table of Contents
- Features
- Table of Contents
- Installation
- Authentication
- Usage
- Initialization
- Select language model
- Generate contents from text
- Generate contents with files
- Conversations across multiple turns
- Continue previous conversations
- Retrieve model's thought process
- Retrieve images in response
- Generate images with Imagen3
- Generate contents with Gemini extensions
- Check and switch to other reply candidates
- Control log level
- References
- Stargazers
Installation
Install/update the package with pip.
pip install -U gemini_webapi
Optionally, package offers a way to automatically import cookies from your local browser. To enable this feature, install browser-cookie3 as well. Supported platforms and browsers can be found here.
pip install -U browser-cookie3
Authentication
- Go to https://gemini.google.com and login with your Google account
- Press F12 for web inspector, go to
Networktab and refresh the page - Click any request and copy cookie values of
__Secure-1PSIDand__Secure-1PSIDTS
services:
main:
volumes:
- ./gemini_cookies:/usr/local/lib/python3.12/site-packages/gemini_webapi/utils/temp
Usage
Initialization
Import required packages and initialize a client with your cookies obtained from the previous step. After a successful initialization, the API will automatically refresh __Secure-1PSIDTS in 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())
Select language model
You can specify which language model to use by passing model argument to GeminiClient.generate_content or GeminiClient.start_chat. The default value is unspecified.
Currently available models (as of Feb 5, 2025):
unspecified- Default modelgemini-2.0-flash- Gemini 2.0 Flashgemini-2.0-flash-thinking- Gemini 2.0 Flash Thinking Experimentalgemini-2.5-flash- Gemini 2.5 Flashgemini-2.5-pro- Gemini 2.5 Pro (daily usage limit imposed)
Models pending update (may not work as expected):
gemini-2.5-exp-advanced- Gemini 2.5 Experimental Advanced (requires Gemini Advanced account)gemini-2.0-exp-advanced- Gemini 2.0 Experimental Advanced (requires Gemini Advanced account)
from gemini_webapi.constants import Model
async def main():
response1 = await client.generate_content(
"What's you language model version? Reply version number only.",
model=Model.G_2_0_FLASH,
)
print(f"Model version ({Model.G_2_0_FLASH.model_name}): {response1.text}")
chat = client.start_chat(model="gemini-2.0-flash-thinking")
response2 = await chat.send_message("What's you language model version? Reply version number only.")
print(f"Model version (gemini-2.0-flash-thinking): {response2.text}")
asyncio.run(main())
Generate contents from text
Ask a one-turn quick question by calling GeminiClient.generate_content.
async def main():
response = await client.generate_content("Hello World!")
print(response.text)
asyncio.run(main())
Generate contents with files
Gemini supports file input, including images and documents. Optionally, you can pass files as a list of paths in str or pathlib.Path to GeminiClient.generate_content together with text prompt.
async def main():
response = await client.generate_content(
"Introduce the contents of these two files. Is there any connection between them?",
files=["assets/sample.pdf", Path("assets/banner.png")],
)
print(response.text)
asyncio.run(main())
Conversations across multiple turns
If you want to keep conversation continuous, please use GeminiClient.start_chat to create a ChatSession object and send messages through it. The conversation history will be automatically handled and get updated after each turn.
async def main():
chat = client.start_chat()
response1 = await chat.send_message(
"Introduce the contents of these two files. Is there any connection between them?",
files=["assets/sample.pdf", Path("assets/banner.png")],
)
print(response1.text)
response2 = await chat.send_message(
"Use image generation tool to modify the banner with another font and design."
)
print(response2.text, response2.images, sep="\n\n----------------------------------\n\n")
asyncio.run(main())
Continue previous conversations
To manually retrieve previous conversations, you can pass previous ChatSession's metadata to GeminiClient.start_chat when creating a new ChatSession. Alternatively, you can persist previous metadata to a file or db if you need to access them after the current Python process has exited.
async def main():
# Start a new chat session
chat = client.start_chat()
response = await chat.send_message("Fine weather today")
# Save chat's metadata
previous_session = chat.metadata
# Load the previous conversation
previous_chat = client.start_chat(metadata=previous_session)
response = await previous_chat.send_message("What was my previous message?")
print(response)
asyncio.run(main())
Retrieve model's thought process
When using models with thinking capabilities, the model's thought process will be populated in ModelOutput.thoughts.
async def main():
response = await client.generate_content(
"What's 1+1?", model="gemini-2.0-flash-thinking"
)
print(response.thoughts)
print(response.text)
asyncio.run(main())
Retrieve images in response
Images in the API's output are stored as a list of Image objects. You can access the image title, URL, and description by calling image.title, image.url and image.alt respectively.
async def main():
response = await client.generate_content("Send me some pictures of cats")
for image in response.images:
print(image, "\n\n----------------------------------\n")
asyncio.run(main())
Generate images with Imagen3
You can ask Gemini to generate and modify images with Imagen3, Google's latest AI image generator, simply by natural language.
You can save images returned from Gemini to local by calling Image.save(). Optionally, you can specify the file path and file name by passing path and filename arguments to the function and skip images with invalid file names by passing skip_invalid_filename=True. Works for both WebImage and GeneratedImage.
async def main():
response = await client.generate_content("Generate some pictures of cats")
for i, image in enumerate(response.images):
await image.save(path="temp/", filename=f"cat_{i}.png", verbose=True)
print(image, "\n\n----------------------------------\n")
asyncio.run(main())
Generate contents with Gemini extensions
After activating extensions for your account, you can access them in your prompts either by natural language or by starting your prompt with "@" followed by the extension keyword.
async def main():
response1 = await client.generate_content("@Gmail What's the latest message in my mailbox?")
print(response1, "\n\n----------------------------------\n")
response2 = await client.generate_content("@Youtube What's the latest activity of Taylor Swift?")
print(response2, "\n\n----------------------------------\n")
asyncio.run(main())
Check and switch to other reply candidates
A response from Gemini usually contains multiple reply candidates with different generated contents. You can check all candidates and choose one to continue the conversation. By default, the first candidate will be chosen automatically.
async def main():
# Start a conversation and list all reply candidates
chat = client.start_chat()
response = await chat.send_message("Recommend a science fiction book for me.")
for candidate in response.candidates:
print(candidate, "\n\n----------------------------------\n")
if len(response.candidates) > 1:
# Control the ongoing conversation flow by choosing candidate manually
new_candidate = chat.choose_candidate(index=1) # Choose the second candidate here
followup_response = await chat.send_message("Tell me more about it.") # Will generate contents based on the chosen candidate
print(new_candidate, followup_response, sep="\n\n----------------------------------\n\n")
else:
print("Only one candidate available.")
asyncio.run(main())
Control log level
You can set the log level of the package to one of the following values: DEBUG, INFO, WARNING, ERROR and CRITICAL. The default value is INFO.
from gemini_webapi import set_log_level
set_log_level("DEBUG")
References
Stargazers
Metadata
Release files for gemini-webapi 1.12.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| gemini_webapi-1.12.3.tar.gz | 250.9 kB | With provenance | Details for gemini_webapi-1.12.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| gemini_webapi-1.12.3-py3-none-any.whl | Python 3 | none | any | Details for gemini_webapi-1.12.3-py3-none-any.whl |
Total release size: 298.5 kB
Release files / gemini_webapi-1.12.3.tar.gz
| Download URL | gemini_webapi-1.12.3.tar.gz |
|---|---|
| Size | 250.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5c915289762c489a76caeb6de30aed4db7176aaf15455f1d6624373d599f13e7
|
|
BLAKE2b-256 checksum How to use checksums |
3a511ed1daa6e6d2de1756d362cc281e1cbf6b7d2ef80db314bfe68c2b7380ea
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.12.8
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on May 25, 2025.
Transparency logRelease files / gemini_webapi-1.12.3-py3-none-any.whl
| Download URL | gemini_webapi-1.12.3-py3-none-any.whl |
|---|---|
| Size | 47.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
8c0ebdaaec58d822038e73057001a891844b9996983db94d846d7e6e8ecee87f
|
|
BLAKE2b-256 checksum How to use checksums |
5b8a5ccbad41269d84e23ade8f93d673b8bb5833c237177030d6f3b3e393a7f9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.12.8
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on May 25, 2025.
Transparency logSecurity for gemini-webapi 1.12.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for gemini_webapi-1.12.3.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on May 25, 2025.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.