├── assets ├── banner.png ├── sample.pdf ├── favicon.png └── logo.svg ├── src └── gemini_webapi │ ├── components │ ├── __init__.py │ └── gem_mixin.py │ ├── __init__.py │ ├── types │ ├── __init__.py │ ├── grpc.py │ ├── modeloutput.py │ ├── candidate.py │ ├── gem.py │ └── image.py │ ├── utils │ ├── __init__.py │ ├── logger.py │ ├── upload_file.py │ ├── decorators.py │ ├── rotate_1psidts.py │ ├── load_browser_cookies.py │ ├── parsing.py │ └── get_access_token.py │ ├── exceptions.py │ ├── constants.py │ └── client.py ├── .github ├── dependabot.yml └── workflows │ ├── github-release.yml │ └── pypi-publish.yml ├── .vscode ├── settings.json └── launch.json ├── pyproject.toml ├── tests ├── test_save_image.py ├── test_gem_mixin.py └── test_client_features.py ├── .gitignore ├── README.md └── LICENSE /assets/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HanaokaYuzu/Gemini-API/HEAD/assets/banner.png -------------------------------------------------------------------------------- /assets/sample.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HanaokaYuzu/Gemini-API/HEAD/assets/sample.pdf -------------------------------------------------------------------------------- /assets/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HanaokaYuzu/Gemini-API/HEAD/assets/favicon.png -------------------------------------------------------------------------------- /src/gemini_webapi/components/__init__.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | 3 | from .gem_mixin import GemMixin 4 | -------------------------------------------------------------------------------- /src/gemini_webapi/__init__.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | 3 | from .client import GeminiClient, ChatSession 4 | from .exceptions import * 5 | from .types import * 6 | from .utils import set_log_level, logger 7 | -------------------------------------------------------------------------------- /src/gemini_webapi/types/__init__.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | 3 | from .candidate import Candidate 4 | from .gem import Gem, GemJar 5 | from .grpc import RPCData 6 | from .image import Image, WebImage, GeneratedImage 7 | from .modeloutput import ModelOutput 8 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "pip" 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | - package-ecosystem: "github-actions" 8 | directory: "/" 9 | schedule: 10 | interval: weekly 11 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.testing.unittestArgs": [ 3 | "-v", 4 | "-s", 5 | "./tests", 6 | "-p", 7 | "test_*.py" 8 | ], 9 | "python.testing.pytestEnabled": false, 10 | "python.testing.unittestEnabled": true, 11 | "markdown.extension.toc.levels": "2..6", 12 | } 13 | -------------------------------------------------------------------------------- /.github/workflows/github-release.yml: -------------------------------------------------------------------------------- 1 | name: Create GitHub Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v[0-9]+.[0-9]+.[0-9]+' 7 | 8 | jobs: 9 | release: 10 | runs-on: ubuntu-latest 11 | permissions: 12 | contents: write 13 | steps: 14 | - uses: actions/checkout@v6 15 | - uses: ncipollo/release-action@v1 16 | with: 17 | body: ${{ github.event.head_commit.message }} 18 | generateReleaseNotes: true 19 | -------------------------------------------------------------------------------- /src/gemini_webapi/utils/__init__.py: -------------------------------------------------------------------------------- 1 | # flake8: noqa 2 | 3 | from asyncio import Task 4 | 5 | from .decorators import running 6 | from .get_access_token import get_access_token 7 | from .load_browser_cookies import load_browser_cookies 8 | from .logger import logger, set_log_level 9 | from .parsing import extract_json_from_response, get_nested_value 10 | from .rotate_1psidts import rotate_1psidts 11 | from .upload_file import upload_file, parse_file_name 12 | 13 | 14 | rotate_tasks: dict[str, Task] = {} 15 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python Debugger: Current File", 9 | "type": "debugpy", 10 | "request": "launch", 11 | "program": "${file}", 12 | "console": "integratedTerminal" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /src/gemini_webapi/types/grpc.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | 3 | from ..constants import GRPC 4 | 5 | 6 | class RPCData(BaseModel): 7 | """ 8 | Helper class containing necessary data for Google RPC calls. 9 | 10 | Parameters 11 | ---------- 12 | rpcid : GRPC 13 | Google RPC ID. 14 | payload : str 15 | Payload for the RPC call. 16 | identifier : str, optional 17 | Identifier/order for the RPC call, defaults to "generic". 18 | Makes sense if there are multiple RPC calls in a batch, where this identifier 19 | can be used to distinguish between responses. 20 | """ 21 | 22 | rpcid: GRPC 23 | payload: str 24 | identifier: str = "generic" 25 | 26 | def __repr__(self): 27 | return f"GRPC(rpcid='{self.rpcid}', payload='{self.payload}', identifier='{self.identifier}')" 28 | 29 | def serialize(self) -> list: 30 | """ 31 | Serializes object into formatted payload ready for RPC call. 32 | """ 33 | 34 | return [self.rpcid, self.payload, None, self.identifier] 35 | -------------------------------------------------------------------------------- /src/gemini_webapi/utils/logger.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from loguru import logger as _logger 3 | 4 | _handler_id = None 5 | 6 | 7 | def set_log_level(level: str | int) -> None: 8 | """ 9 | Set the log level for gemini_webapi. The default log level is "INFO". 10 | 11 | Note: calling this function for the first time will globally remove all existing loguru 12 | handlers. To avoid this, you may want to set logging behaviors directly with loguru. 13 | 14 | Parameters 15 | ---------- 16 | level : `str | int` 17 | Log level: "TRACE", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL" 18 | 19 | Examples 20 | -------- 21 | >>> from gemini_webapi import set_log_level 22 | >>> set_log_level("DEBUG") # Show debug messages 23 | >>> set_log_level("ERROR") # Only show errors 24 | """ 25 | 26 | global _handler_id 27 | 28 | _logger.remove(_handler_id) 29 | 30 | _handler_id = _logger.add( 31 | sys.stderr, 32 | level=level, 33 | filter=lambda record: record["extra"].get("name") == "gemini_webapi", 34 | ) 35 | 36 | 37 | logger = _logger.bind(name="gemini_webapi") 38 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=69", "setuptools_scm>=8"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "gemini-webapi" 7 | authors = [ 8 | {name = "UZQueen"}, 9 | ] 10 | description = "✨ An elegant async Python wrapper for Google Gemini web app" 11 | readme = "README.md" 12 | license = {file = "LICENSE"} 13 | keywords = ["API", "async", "Gemini", "Bard", "Google", "Generative AI", "LLM"] 14 | classifiers = [ 15 | "Development Status :: 4 - Beta", 16 | "Intended Audience :: Developers", 17 | "Programming Language :: Python :: 3", 18 | "Programming Language :: Python :: 3.11", 19 | "Programming Language :: Python :: 3.12", 20 | ] 21 | requires-python = ">=3.10" 22 | dependencies = [ 23 | "httpx~=0.28.1", 24 | "loguru~=0.7.3", 25 | "orjson~=3.11.1", 26 | "pydantic~=2.12.2", 27 | ] 28 | dynamic = ["version"] 29 | 30 | [project.urls] 31 | Repository = "https://github.com/HanaokaYuzu/Gemini-API" 32 | Issues = "https://github.com/HanaokaYuzu/Gemini-API/issues" 33 | 34 | [tool.setuptools.packages.find] 35 | where = ["src"] 36 | include = ["gemini_webapi"] 37 | 38 | [tool.setuptools_scm] 39 | version_scheme = "post-release" 40 | local_scheme = "no-local-version" 41 | -------------------------------------------------------------------------------- /src/gemini_webapi/exceptions.py: -------------------------------------------------------------------------------- 1 | class AuthError(Exception): 2 | """ 3 | Exception for authentication errors caused by invalid credentials/cookies. 4 | """ 5 | 6 | pass 7 | 8 | 9 | class APIError(Exception): 10 | """ 11 | Exception for package-level errors which need to be fixed in the future development (e.g. validation errors). 12 | """ 13 | 14 | pass 15 | 16 | 17 | class ImageGenerationError(APIError): 18 | """ 19 | Exception for generated image parsing errors. 20 | """ 21 | 22 | pass 23 | 24 | 25 | class GeminiError(Exception): 26 | """ 27 | Exception for errors returned from Gemini server which are not handled by the package. 28 | """ 29 | 30 | pass 31 | 32 | 33 | class TimeoutError(GeminiError): 34 | """ 35 | Exception for request timeouts. 36 | """ 37 | 38 | pass 39 | 40 | 41 | class UsageLimitExceeded(GeminiError): 42 | """ 43 | Exception for model usage limit exceeded errors. 44 | """ 45 | 46 | pass 47 | 48 | 49 | class ModelInvalid(GeminiError): 50 | """ 51 | Exception for invalid model header string errors. 52 | """ 53 | 54 | pass 55 | 56 | 57 | class TemporarilyBlocked(GeminiError): 58 | """ 59 | Exception for 429 Too Many Requests when IP is temporarily blocked. 60 | """ 61 | 62 | pass 63 | -------------------------------------------------------------------------------- /src/gemini_webapi/types/modeloutput.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | 3 | from .image import Image 4 | from .candidate import Candidate 5 | 6 | 7 | class ModelOutput(BaseModel): 8 | """ 9 | Classified output from gemini.google.com 10 | 11 | Parameters 12 | ---------- 13 | metadata: `list[str]` 14 | List of chat metadata `[cid, rid, rcid]`, can be shorter than 3 elements, like `[cid, rid]` or `[cid]` only 15 | candidates: `list[Candidate]` 16 | List of all candidates returned from gemini 17 | chosen: `int`, optional 18 | Index of the chosen candidate, by default will choose the first one 19 | """ 20 | 21 | metadata: list[str] 22 | candidates: list[Candidate] 23 | chosen: int = 0 24 | 25 | def __str__(self): 26 | return self.text 27 | 28 | def __repr__(self): 29 | return f"ModelOutput(metadata={self.metadata}, chosen={self.chosen}, candidates={self.candidates})" 30 | 31 | @property 32 | def text(self) -> str: 33 | return self.candidates[self.chosen].text 34 | 35 | @property 36 | def thoughts(self) -> str | None: 37 | return self.candidates[self.chosen].thoughts 38 | 39 | @property 40 | def images(self) -> list[Image]: 41 | return self.candidates[self.chosen].images 42 | 43 | @property 44 | def rcid(self) -> str: 45 | return self.candidates[self.chosen].rcid 46 | -------------------------------------------------------------------------------- /.github/workflows/pypi-publish.yml: -------------------------------------------------------------------------------- 1 | name: Build and Publish 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v[0-9]+.[0-9]+.[0-9]+' 7 | workflow_dispatch: 8 | inputs: 9 | logLevel: 10 | description: 'Log level' 11 | required: true 12 | default: 'warning' 13 | type: choice 14 | options: 15 | - info 16 | - warning 17 | - debug 18 | 19 | permissions: 20 | contents: read 21 | 22 | jobs: 23 | build: 24 | name: Build package 25 | runs-on: ubuntu-latest 26 | steps: 27 | - uses: actions/checkout@v6 28 | - name: Set up Python 29 | uses: actions/setup-python@v6 30 | with: 31 | python-version: '3.x' 32 | - name: Install dependencies 33 | run: | 34 | python -m pip install --upgrade pip 35 | pip install build 36 | - name: Build package 37 | run: python -m build 38 | - name: Archive production artifacts 39 | uses: actions/upload-artifact@v5.0.0 40 | with: 41 | name: dist 42 | path: dist 43 | 44 | pypi-publish: 45 | name: Upload release to PyPI 46 | needs: build 47 | runs-on: ubuntu-latest 48 | environment: 49 | name: pypi 50 | url: https://pypi.org/p/gemini-webapi 51 | permissions: 52 | id-token: write # IMPORTANT: this permission is mandatory for trusted publishing 53 | steps: 54 | - name: Retrieve built artifacts 55 | uses: actions/download-artifact@v6.0.0 56 | with: 57 | name: dist 58 | path: dist 59 | - name: Publish package distributions to PyPI 60 | uses: pypa/gh-action-pypi-publish@v1.13.0 61 | -------------------------------------------------------------------------------- /src/gemini_webapi/types/candidate.py: -------------------------------------------------------------------------------- 1 | import html 2 | from pydantic import BaseModel, field_validator 3 | 4 | from .image import Image, WebImage, GeneratedImage 5 | 6 | 7 | class Candidate(BaseModel): 8 | """ 9 | A single reply candidate object in the model output. A full response from Gemini usually contains multiple reply candidates. 10 | 11 | Parameters 12 | ---------- 13 | rcid: `str` 14 | Reply candidate ID to build the metadata 15 | text: `str` 16 | Text output 17 | thoughts: `str`, optional 18 | Model's thought process, can be empty. Only populated with `-thinking` models 19 | web_images: `list[WebImage]`, optional 20 | List of web images in reply, can be empty. 21 | generated_images: `list[GeneratedImage]`, optional 22 | List of generated images in reply, can be empty 23 | """ 24 | 25 | rcid: str 26 | text: str 27 | thoughts: str | None = None 28 | web_images: list[WebImage] = [] 29 | generated_images: list[GeneratedImage] = [] 30 | 31 | def __str__(self): 32 | return self.text 33 | 34 | def __repr__(self): 35 | return f"Candidate(rcid='{self.rcid}', text='{len(self.text) <= 20 and self.text or self.text[:20] + '...'}', images={self.images})" 36 | 37 | @field_validator("text", "thoughts") 38 | @classmethod 39 | def decode_html(cls, value: str) -> str: 40 | """ 41 | Auto unescape HTML entities in text/thoughts if any. 42 | """ 43 | 44 | if value: 45 | value = html.unescape(value) 46 | return value 47 | 48 | @property 49 | def images(self) -> list[Image]: 50 | return self.web_images + self.generated_images 51 | -------------------------------------------------------------------------------- /src/gemini_webapi/utils/upload_file.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | from httpx import AsyncClient 4 | from pydantic import validate_call 5 | 6 | from ..constants import Endpoint, Headers 7 | 8 | 9 | @validate_call 10 | async def upload_file(file: str | Path, proxy: str | None = None) -> str: 11 | """ 12 | Upload a file to Google's server and return its identifier. 13 | 14 | Parameters 15 | ---------- 16 | file : `str` | `Path` 17 | Path to the file to be uploaded. 18 | proxy: `str`, optional 19 | Proxy URL. 20 | 21 | Returns 22 | ------- 23 | `str` 24 | Identifier of the uploaded file. 25 | E.g. "/contrib_service/ttl_1d/1709764705i7wdlyx3mdzndme3a767pluckv4flj" 26 | 27 | Raises 28 | ------ 29 | `httpx.HTTPStatusError` 30 | If the upload request failed. 31 | """ 32 | 33 | with open(file, "rb") as f: 34 | file = f.read() 35 | 36 | async with AsyncClient(proxy=proxy) as client: 37 | response = await client.post( 38 | url=Endpoint.UPLOAD.value, 39 | headers=Headers.UPLOAD.value, 40 | files={"file": file}, 41 | follow_redirects=True, 42 | ) 43 | response.raise_for_status() 44 | return response.text 45 | 46 | 47 | def parse_file_name(file: str | Path) -> str: 48 | """ 49 | Parse the file name from the given path. 50 | 51 | Parameters 52 | ---------- 53 | file : `str` | `Path` 54 | Path to the file. 55 | 56 | Returns 57 | ------- 58 | `str` 59 | File name with extension. 60 | """ 61 | 62 | file = Path(file) 63 | if not file.is_file(): 64 | raise ValueError(f"{file} is not a valid file.") 65 | 66 | return file.name 67 | -------------------------------------------------------------------------------- /tests/test_save_image.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | import logging 4 | 5 | from httpx import HTTPError 6 | 7 | from gemini_webapi import GeminiClient, AuthError, set_log_level, logger 8 | 9 | logging.getLogger("asyncio").setLevel(logging.ERROR) 10 | set_log_level("DEBUG") 11 | 12 | 13 | class TestGeminiClient(unittest.IsolatedAsyncioTestCase): 14 | async def asyncSetUp(self): 15 | self.geminiclient = GeminiClient( 16 | os.getenv("SECURE_1PSID"), os.getenv("SECURE_1PSIDTS") 17 | ) 18 | 19 | try: 20 | await self.geminiclient.init(auto_refresh=False) 21 | except AuthError: 22 | self.skipTest("Test was skipped due to invalid cookies") 23 | 24 | async def test_save_web_image(self): 25 | response = await self.geminiclient.generate_content( 26 | "Show me some pictures of random subjects" 27 | ) 28 | self.assertTrue(response.images) 29 | for image in response.images: 30 | try: 31 | await image.save(verbose=True, skip_invalid_filename=True) 32 | except HTTPError as e: 33 | logger.warning(e) 34 | 35 | async def test_save_generated_image(self): 36 | response = await self.geminiclient.generate_content( 37 | "Generate a picture of random subjects" 38 | ) 39 | self.assertTrue(response.images) 40 | for image in response.images: 41 | await image.save(verbose=True, full_size=True) 42 | 43 | async def test_save_image_to_image(self): 44 | response = await self.geminiclient.generate_content( 45 | "Design an application icon based on the provided image. Make it simple and modern.", 46 | files=["assets/banner.png"], 47 | ) 48 | self.assertTrue(response.images) 49 | for image in response.images: 50 | await image.save(verbose=True, full_size=True) 51 | 52 | 53 | if __name__ == "__main__": 54 | unittest.main() 55 | -------------------------------------------------------------------------------- /src/gemini_webapi/utils/decorators.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import functools 3 | from collections.abc import Callable 4 | 5 | from ..exceptions import APIError, ImageGenerationError 6 | 7 | 8 | def running(retry: int = 0) -> Callable: 9 | """ 10 | Decorator to check if GeminiClient is running before making a request. 11 | 12 | Parameters 13 | ---------- 14 | retry: `int`, optional 15 | Max number of retries when `gemini_webapi.APIError` is raised. 16 | """ 17 | 18 | def decorator(func): 19 | @functools.wraps(func) 20 | async def wrapper(client, *args, retry=retry, **kwargs): 21 | try: 22 | if not client._running: 23 | await client.init( 24 | timeout=client.timeout, 25 | auto_close=client.auto_close, 26 | close_delay=client.close_delay, 27 | auto_refresh=client.auto_refresh, 28 | refresh_interval=client.refresh_interval, 29 | verbose=False, 30 | ) 31 | if client._running: 32 | return await func(client, *args, **kwargs) 33 | 34 | # Should not reach here 35 | raise APIError( 36 | f"Invalid function call: GeminiClient.{func.__name__}. Client initialization failed." 37 | ) 38 | else: 39 | return await func(client, *args, **kwargs) 40 | except APIError as e: 41 | # Image generation takes too long, only retry once 42 | if isinstance(e, ImageGenerationError): 43 | retry = min(1, retry) 44 | 45 | if retry > 0: 46 | await asyncio.sleep(1) 47 | return await wrapper(client, *args, retry=retry - 1, **kwargs) 48 | 49 | raise 50 | 51 | return wrapper 52 | 53 | return decorator 54 | -------------------------------------------------------------------------------- /src/gemini_webapi/utils/rotate_1psidts.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | from pathlib import Path 4 | 5 | from httpx import AsyncClient 6 | 7 | from ..constants import Endpoint, Headers 8 | from ..exceptions import AuthError 9 | 10 | 11 | async def rotate_1psidts(cookies: dict, proxy: str | None = None) -> str: 12 | """ 13 | Refresh the __Secure-1PSIDTS cookie and store the refreshed cookie value in cache file. 14 | 15 | Parameters 16 | ---------- 17 | cookies : `dict` 18 | Cookies to be used in the request. 19 | proxy: `str`, optional 20 | Proxy URL. 21 | 22 | Returns 23 | ------- 24 | `str` 25 | New value of the __Secure-1PSIDTS cookie. 26 | 27 | Raises 28 | ------ 29 | `gemini_webapi.AuthError` 30 | If request failed with 401 Unauthorized. 31 | `httpx.HTTPStatusError` 32 | If request failed with other status codes. 33 | """ 34 | 35 | path = ( 36 | (GEMINI_COOKIE_PATH := os.getenv("GEMINI_COOKIE_PATH")) 37 | and Path(GEMINI_COOKIE_PATH) 38 | or (Path(__file__).parent / "temp") 39 | ) 40 | path.mkdir(parents=True, exist_ok=True) 41 | filename = f".cached_1psidts_{cookies['__Secure-1PSID']}.txt" 42 | path = path / filename 43 | 44 | # Check if the cache file was modified in the last minute to avoid 429 Too Many Requests 45 | if not (path.is_file() and time.time() - os.path.getmtime(path) <= 60): 46 | async with AsyncClient(proxy=proxy) as client: 47 | response = await client.post( 48 | url=Endpoint.ROTATE_COOKIES.value, 49 | headers=Headers.ROTATE_COOKIES.value, 50 | cookies=cookies, 51 | data='[000,"-0000000000000000000"]', 52 | ) 53 | if response.status_code == 401: 54 | raise AuthError 55 | response.raise_for_status() 56 | 57 | if new_1psidts := response.cookies.get("__Secure-1PSIDTS"): 58 | path.write_text(new_1psidts) 59 | return new_1psidts 60 | -------------------------------------------------------------------------------- /src/gemini_webapi/utils/load_browser_cookies.py: -------------------------------------------------------------------------------- 1 | from http.cookiejar import CookieJar 2 | 3 | from .logger import logger 4 | 5 | 6 | def load_browser_cookies(domain_name: str = "", verbose=True) -> dict: 7 | """ 8 | Try to load cookies from all supported browsers and return combined cookiejar. 9 | Optionally pass in a domain name to only load cookies from the specified domain. 10 | 11 | Parameters 12 | ---------- 13 | domain_name : str, optional 14 | Domain name to filter cookies by, by default will load all cookies without filtering. 15 | verbose : bool, optional 16 | If `True`, will print more infomation in logs. 17 | 18 | Returns 19 | ------- 20 | `dict[str, dict]` 21 | Dictionary with browser as keys and their cookies for the specified domain as values. 22 | Only browsers that have cookies for the specified domain will be included. 23 | """ 24 | 25 | import browser_cookie3 as bc3 26 | 27 | cookies = {} 28 | for cookie_fn in [ 29 | bc3.chrome, 30 | bc3.chromium, 31 | bc3.opera, 32 | bc3.opera_gx, 33 | bc3.brave, 34 | bc3.edge, 35 | bc3.vivaldi, 36 | bc3.firefox, 37 | bc3.librewolf, 38 | bc3.safari, 39 | ]: 40 | try: 41 | jar: CookieJar = cookie_fn(domain_name=domain_name) 42 | if jar: 43 | cookies[cookie_fn.__name__] = { 44 | cookie.name: cookie.value for cookie in jar 45 | } 46 | except bc3.BrowserCookieError: 47 | pass 48 | except PermissionError as e: 49 | if verbose: 50 | logger.warning( 51 | f"Permission denied while trying to load cookies from {cookie_fn.__name__}. {e}" 52 | ) 53 | except Exception as e: 54 | if verbose: 55 | logger.error( 56 | f"Error happened while trying to load cookies from {cookie_fn.__name__}. {e}" 57 | ) 58 | 59 | return cookies 60 | -------------------------------------------------------------------------------- /assets/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/gemini_webapi/utils/parsing.py: -------------------------------------------------------------------------------- 1 | from typing import Any 2 | 3 | import orjson as json 4 | 5 | from .logger import logger 6 | 7 | 8 | def get_nested_value(data: list, path: list[int], default: Any = None) -> Any: 9 | """ 10 | Safely get a value from a nested list by a sequence of indices. 11 | 12 | Parameters 13 | ---------- 14 | data: `list` 15 | The nested list to traverse. 16 | path: `list[int]` 17 | A list of indices representing the path to the desired value. 18 | default: `Any`, optional 19 | The default value to return if the path is not found. 20 | """ 21 | 22 | current = data 23 | 24 | for i, key in enumerate(path): 25 | try: 26 | current = current[key] 27 | except (IndexError, TypeError, KeyError): 28 | current_repr = repr(current) 29 | if len(current_repr) > 200: 30 | current_repr = f"{current_repr[:197]}..." 31 | 32 | logger.debug( 33 | f"Safe navigation: path {path} ended at index {i} (key '{key}'), " 34 | f"returning default. Context: {current_repr}" 35 | ) 36 | 37 | return default 38 | 39 | if current is None and default is not None: 40 | return default 41 | 42 | return current 43 | 44 | 45 | def extract_json_from_response(text: str) -> list: 46 | """ 47 | Clean and extract the JSON content from a Google API response. 48 | 49 | Parameters 50 | ---------- 51 | text: `str` 52 | The raw response text from a Google API. 53 | 54 | Returns 55 | ------- 56 | `list` 57 | The extracted JSON array or object (should be an array). 58 | 59 | Raises 60 | ------ 61 | `TypeError` 62 | If the input is not a string. 63 | `ValueError` 64 | If no JSON object is found or the response is empty. 65 | """ 66 | 67 | if not isinstance(text, str): 68 | raise TypeError( 69 | f"Input text is expected to be a string, got {type(text).__name__} instead." 70 | ) 71 | 72 | # Find the first line which is valid JSON 73 | for line in text.splitlines(): 74 | try: 75 | return json.loads(line.strip()) 76 | except json.JSONDecodeError: 77 | continue 78 | 79 | # If no JSON is found, raise ValueError 80 | raise ValueError("Could not find a valid JSON object or array in the response.") 81 | -------------------------------------------------------------------------------- /tests/test_gem_mixin.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | import unittest 4 | import logging 5 | 6 | from gemini_webapi import GeminiClient, set_log_level, logger 7 | from gemini_webapi.exceptions import AuthError 8 | 9 | logging.getLogger("asyncio").setLevel(logging.ERROR) 10 | set_log_level("DEBUG") 11 | 12 | 13 | class TestGemMixin(unittest.IsolatedAsyncioTestCase): 14 | async def asyncSetUp(self): 15 | self.geminiclient = GeminiClient( 16 | os.getenv("SECURE_1PSID"), os.getenv("SECURE_1PSIDTS"), verify=False 17 | ) 18 | 19 | try: 20 | await self.geminiclient.init(auto_refresh=False) 21 | except AuthError as e: 22 | self.skipTest(e) 23 | 24 | @logger.catch(reraise=True) 25 | async def test_fetch_gems(self): 26 | await self.geminiclient.fetch_gems(include_hidden=False) 27 | gems = self.geminiclient.gems 28 | self.assertTrue(len(gems.filter(predefined=True)) > 0) 29 | for gem in gems: 30 | logger.debug(gem) 31 | 32 | custom_gems = gems.filter(predefined=False) 33 | if custom_gems: 34 | logger.debug(f"Found {len(custom_gems)} custom gems:") 35 | for gem in custom_gems: 36 | logger.debug(gem) 37 | 38 | @logger.catch(reraise=True) 39 | async def test_create_gem(self): 40 | gem = await self.geminiclient.create_gem( 41 | name="Test Gem", 42 | prompt="Gemini API has launched creating gem functionality on Aug 1st, 2025", 43 | description="This gem is used for testing the functionality of Gemini API", 44 | ) 45 | logger.debug(f"Gem created: {gem}") 46 | 47 | @logger.catch(reraise=True) 48 | async def test_update_gem(self): 49 | await self.geminiclient.fetch_gems() 50 | custom_gems = self.geminiclient.gems.filter(predefined=False) 51 | if not custom_gems: 52 | self.skipTest("No custom gems available to update.") 53 | 54 | last_created_gem = next(iter(custom_gems.values())) 55 | randint = random.randint(0, 100) 56 | updated_gem = await self.geminiclient.update_gem( 57 | last_created_gem.id, 58 | name="Updated Test Gem", 59 | prompt="Updated prompt for the gem.", 60 | description=f"{randint}", 61 | ) 62 | logger.debug(f"Gem updated: {updated_gem}") 63 | 64 | await self.geminiclient.fetch_gems() 65 | custom_gems = self.geminiclient.gems.filter(predefined=False) 66 | last_created_gem = next(iter(custom_gems.values())) 67 | self.assertEqual(last_created_gem.description, updated_gem.description) 68 | 69 | @logger.catch(reraise=True) 70 | async def test_delete_gem(self): 71 | await self.geminiclient.fetch_gems() 72 | custom_gems = self.geminiclient.gems.filter(predefined=False) 73 | total_before_deletion = len(custom_gems) 74 | if total_before_deletion == 0: 75 | self.skipTest("No custom gems available to delete.") 76 | 77 | last_created_gem = next(iter(custom_gems.values())) 78 | await self.geminiclient.delete_gem(last_created_gem.id) 79 | logger.debug(f"Gem deleted: {last_created_gem}") 80 | 81 | await self.geminiclient.fetch_gems() 82 | custom_gems = self.geminiclient.gems.filter(predefined=False) 83 | total_after_deletion = len(custom_gems) 84 | self.assertEqual(total_after_deletion, total_before_deletion - 1) 85 | 86 | 87 | if __name__ == "__main__": 88 | unittest.main() 89 | -------------------------------------------------------------------------------- /src/gemini_webapi/constants.py: -------------------------------------------------------------------------------- 1 | from enum import Enum, IntEnum, StrEnum 2 | 3 | 4 | class Endpoint(StrEnum): 5 | GOOGLE = "https://www.google.com" 6 | INIT = "https://gemini.google.com/app" 7 | GENERATE = "https://gemini.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate" 8 | ROTATE_COOKIES = "https://accounts.google.com/RotateCookies" 9 | UPLOAD = "https://content-push.googleapis.com/upload" 10 | BATCH_EXEC = "https://gemini.google.com/_/BardChatUi/data/batchexecute" 11 | 12 | 13 | class GRPC(StrEnum): 14 | """ 15 | Google RPC ids used in Gemini API. 16 | """ 17 | 18 | # Chat methods 19 | LIST_CHATS = "MaZiqc" 20 | READ_CHAT = "hNvQHb" 21 | 22 | # Gem methods 23 | LIST_GEMS = "CNgdBe" 24 | CREATE_GEM = "oMH3Zd" 25 | UPDATE_GEM = "kHv0Vd" 26 | DELETE_GEM = "UXcSJb" 27 | 28 | 29 | class Headers(Enum): 30 | GEMINI = { 31 | "Content-Type": "application/x-www-form-urlencoded;charset=utf-8", 32 | "Host": "gemini.google.com", 33 | "Origin": "https://gemini.google.com", 34 | "Referer": "https://gemini.google.com/", 35 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", 36 | "X-Same-Domain": "1", 37 | } 38 | ROTATE_COOKIES = { 39 | "Content-Type": "application/json", 40 | } 41 | UPLOAD = {"Push-ID": "feeds/mcudyrk2a4khkz"} 42 | 43 | 44 | class Model(Enum): 45 | UNSPECIFIED = ("unspecified", {}, False) 46 | G_3_0_PRO = ( 47 | "gemini-3.0-pro", 48 | { 49 | "x-goog-ext-525001261-jspb": '[1,null,null,null,"9d8ca3786ebdfbea",null,null,0,[4]]' 50 | }, 51 | False, 52 | ) 53 | G_2_5_PRO = ( 54 | "gemini-2.5-pro", 55 | { 56 | "x-goog-ext-525001261-jspb": '[1,null,null,null,"4af6c7f5da75d65d",null,null,0,[4]]' 57 | }, 58 | False, 59 | ) 60 | G_2_5_FLASH = ( 61 | "gemini-2.5-flash", 62 | { 63 | "x-goog-ext-525001261-jspb": '[1,null,null,null,"9ec249fc9ad08861",null,null,0,[4]]' 64 | }, 65 | False, 66 | ) 67 | 68 | def __init__(self, name, header, advanced_only): 69 | self.model_name = name 70 | self.model_header = header 71 | self.advanced_only = advanced_only 72 | 73 | @classmethod 74 | def from_name(cls, name: str): 75 | for model in cls: 76 | if model.model_name == name: 77 | return model 78 | 79 | raise ValueError( 80 | f"Unknown model name: {name}. Available models: {', '.join([model.model_name for model in cls])}" 81 | ) 82 | 83 | @classmethod 84 | def from_dict(cls, model_dict: dict): 85 | if "model_name" not in model_dict or "model_header" not in model_dict: 86 | raise ValueError( 87 | "When passing a custom model as a dictionary, 'model_name' and 'model_header' keys must be provided." 88 | ) 89 | 90 | if not isinstance(model_dict["model_header"], dict): 91 | raise ValueError( 92 | "When passing a custom model as a dictionary, 'model_header' must be a dictionary containing valid header strings." 93 | ) 94 | 95 | custom_model = cls.UNSPECIFIED 96 | custom_model.model_name = model_dict["model_name"] 97 | custom_model.model_header = model_dict["model_header"] 98 | return custom_model 99 | 100 | 101 | class ErrorCode(IntEnum): 102 | """ 103 | Known error codes returned from server. 104 | """ 105 | 106 | TEMPORARY_ERROR_1013 = 1013 # Randomly raised when generating with certain models, but disappears soon after 107 | USAGE_LIMIT_EXCEEDED = 1037 108 | MODEL_INCONSISTENT = 1050 109 | MODEL_HEADER_INVALID = 1052 110 | IP_TEMPORARILY_BLOCKED = 1060 111 | -------------------------------------------------------------------------------- /src/gemini_webapi/types/gem.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | 3 | 4 | class Gem(BaseModel): 5 | """ 6 | Reusable Gemini Gem object working as a system prompt, providing additional context to the model. 7 | Gemini provides a set of predefined gems, and users can create custom gems as well. 8 | 9 | Parameters 10 | ---------- 11 | id: `str` 12 | Unique identifier for the gem. 13 | name: `str` 14 | User-friendly name of the gem. 15 | description: `str`, optional 16 | Brief description of the gem's purpose or content. 17 | prompt: `str`, optional 18 | The system prompt text that the gem provides to the model. 19 | predefined: `bool` 20 | Indicates whether the gem is predefined by Gemini or created by the user. 21 | """ 22 | 23 | id: str 24 | name: str 25 | description: str | None = None 26 | prompt: str | None = None 27 | predefined: bool 28 | 29 | def __str__(self) -> str: 30 | return ( 31 | f"Gem(id='{self.id}', name='{self.name}', description='{self.description}', " 32 | f"prompt='{self.prompt}', predefined={self.predefined})" 33 | ) 34 | 35 | 36 | class GemJar(dict[str, Gem]): 37 | """ 38 | Helper class for handling a collection of `Gem` objects, stored by their ID. 39 | This class extends `dict` to allows retrieving gems with extra filtering options. 40 | """ 41 | 42 | def __iter__(self): 43 | """ 44 | Iter over the gems in the jar. 45 | """ 46 | 47 | return self.values().__iter__() 48 | 49 | def get( 50 | self, id: str | None = None, name: str | None = None, default: Gem | None = None 51 | ) -> Gem | None: 52 | """ 53 | Retrieves a gem by its id and/or name. 54 | If both id and name are provided, returns the gem that matches both id and name. 55 | If only id is provided, it's a direct lookup. 56 | If only name is provided, it searches through the gems. 57 | 58 | Parameters 59 | ---------- 60 | id: `str`, optional 61 | The unique identifier of the gem to retrieve. 62 | name: `str`, optional 63 | The user-friendly name of the gem to retrieve. 64 | default: `Gem`, optional 65 | The default value to return if no matching gem is found. 66 | 67 | Returns 68 | ------- 69 | `Gem` | None 70 | The matching gem if found, otherwise return the default value. 71 | 72 | Raises 73 | ------ 74 | `AssertionError` 75 | If neither id nor name is provided. 76 | """ 77 | 78 | assert not ( 79 | id is None and name is None 80 | ), "At least one of gem id or name must be provided." 81 | 82 | if id is not None: 83 | gem_candidate = super().get(id) 84 | if gem_candidate: 85 | if name is not None: 86 | if gem_candidate.name == name: 87 | return gem_candidate 88 | else: 89 | return default 90 | else: 91 | return gem_candidate 92 | else: 93 | return default 94 | elif name is not None: 95 | for gem_obj in self.values(): 96 | if gem_obj.name == name: 97 | return gem_obj 98 | return default 99 | 100 | # Should be unreachable due to the assertion. 101 | return default 102 | 103 | def filter( 104 | self, predefined: bool | None = None, name: str | None = None 105 | ) -> "GemJar": 106 | """ 107 | Returns a new `GemJar` containing gems that match the given filters. 108 | 109 | Parameters 110 | ---------- 111 | predefined: `bool`, optional 112 | If provided, filters gems by whether they are predefined (True) or user-created (False). 113 | name: `str`, optional 114 | If provided, filters gems by their name (exact match). 115 | 116 | Returns 117 | ------- 118 | `GemJar` 119 | A new `GemJar` containing the filtered gems. Can be empty if no gems match the criteria. 120 | """ 121 | 122 | filtered_gems = GemJar() 123 | 124 | for gem_id, gem in self.items(): 125 | if predefined is not None and gem.predefined != predefined: 126 | continue 127 | if name is not None and gem.name != name: 128 | continue 129 | 130 | filtered_gems[gem_id] = gem 131 | 132 | return GemJar(filtered_gems) 133 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | .vscode/* 163 | !.vscode/settings.json 164 | !.vscode/tasks.json 165 | !.vscode/launch.json 166 | !.vscode/extensions.json 167 | !.vscode/*.code-snippets 168 | 169 | # Local History for Visual Studio Code 170 | .history/ 171 | 172 | # Built Visual Studio Code Extensions 173 | *.vsix 174 | 175 | # General 176 | .DS_Store 177 | .AppleDouble 178 | .LSOverride 179 | 180 | # Icon must end with two \r 181 | Icon 182 | 183 | 184 | # Thumbnails 185 | ._* 186 | 187 | # Files that might appear in the root of a volume 188 | .DocumentRevisions-V100 189 | .fseventsd 190 | .Spotlight-V100 191 | .TemporaryItems 192 | .Trashes 193 | .VolumeIcon.icns 194 | .com.apple.timemachine.donotpresent 195 | 196 | # Directories potentially created on remote AFP share 197 | .AppleDB 198 | .AppleDesktop 199 | Network Trash Folder 200 | Temporary Items 201 | .apdisk 202 | 203 | # Temporary files 204 | .temp/ 205 | -------------------------------------------------------------------------------- /src/gemini_webapi/types/image.py: -------------------------------------------------------------------------------- 1 | import re 2 | from pathlib import Path 3 | from datetime import datetime 4 | 5 | from httpx import AsyncClient, HTTPError 6 | from pydantic import BaseModel, field_validator 7 | 8 | from ..utils import logger 9 | 10 | 11 | class Image(BaseModel): 12 | """ 13 | A single image object returned from Gemini. 14 | 15 | Parameters 16 | ---------- 17 | url: `str` 18 | URL of the image. 19 | title: `str`, optional 20 | Title of the image, by default is "[Image]". 21 | alt: `str`, optional 22 | Optional description of the image. 23 | proxy: `str`, optional 24 | Proxy used when saving image. 25 | """ 26 | 27 | url: str 28 | title: str = "[Image]" 29 | alt: str = "" 30 | proxy: str | None = None 31 | 32 | def __str__(self): 33 | return ( 34 | f"Image(title='{self.title}', alt='{self.alt}', " 35 | f"url='{len(self.url) <= 20 and self.url or self.url[:8] + '...' + self.url[-12:]}')" 36 | ) 37 | 38 | async def save( 39 | self, 40 | path: str = "temp", 41 | filename: str | None = None, 42 | cookies: dict | None = None, 43 | verbose: bool = False, 44 | skip_invalid_filename: bool = False, 45 | ) -> str | None: 46 | """ 47 | Save the image to disk. 48 | 49 | Parameters 50 | ---------- 51 | path: `str`, optional 52 | Path to save the image, by default will save to "./temp". 53 | filename: `str`, optional 54 | File name to save the image, by default will use the original file name from the URL. 55 | cookies: `dict`, optional 56 | Cookies used for requesting the content of the image. 57 | verbose : `bool`, optional 58 | If True, will print the path of the saved file or warning for invalid file name, by default False. 59 | skip_invalid_filename: `bool`, optional 60 | If True, will only save the image if the file name and extension are valid, by default False. 61 | 62 | Returns 63 | ------- 64 | `str | None` 65 | Absolute path of the saved image if successful, None if filename is invalid and `skip_invalid_filename` is True. 66 | 67 | Raises 68 | ------ 69 | `httpx.HTTPError` 70 | If the network request failed. 71 | """ 72 | 73 | filename = filename or self.url.split("/")[-1].split("?")[0] 74 | match = re.search(r"^(.*\.\w+)", filename) 75 | if match: 76 | filename = match.group() 77 | else: 78 | if verbose: 79 | logger.warning(f"Invalid filename: {filename}") 80 | if skip_invalid_filename: 81 | return None 82 | 83 | async with AsyncClient( 84 | follow_redirects=True, cookies=cookies, proxy=self.proxy 85 | ) as client: 86 | response = await client.get(self.url) 87 | if response.status_code == 200: 88 | content_type = response.headers.get("content-type") 89 | if content_type and "image" not in content_type: 90 | logger.warning( 91 | f"Content type of {filename} is not image, but {content_type}." 92 | ) 93 | 94 | path = Path(path) 95 | path.mkdir(parents=True, exist_ok=True) 96 | 97 | dest = path / filename 98 | dest.write_bytes(response.content) 99 | 100 | if verbose: 101 | logger.info(f"Image saved as {dest.resolve()}") 102 | 103 | return str(dest.resolve()) 104 | else: 105 | raise HTTPError( 106 | f"Error downloading image: {response.status_code} {response.reason_phrase}" 107 | ) 108 | 109 | 110 | class WebImage(Image): 111 | """ 112 | Image retrieved from web. Returned when ask Gemini to "SEND an image of [something]". 113 | """ 114 | 115 | pass 116 | 117 | 118 | class GeneratedImage(Image): 119 | """ 120 | Image generated by ImageFX, Google's AI image generator. Returned when ask Gemini to "GENERATE an image of [something]". 121 | 122 | Parameters 123 | ---------- 124 | cookies: `dict` 125 | Cookies used for requesting the content of the generated image, inherit from GeminiClient object or manually set. 126 | Should contain valid "__Secure-1PSID" and "__Secure-1PSIDTS" values. 127 | """ 128 | 129 | cookies: dict[str, str] 130 | 131 | @field_validator("cookies") 132 | @classmethod 133 | def validate_cookies(cls, v: dict) -> dict: 134 | if len(v) == 0: 135 | raise ValueError( 136 | "GeneratedImage is designed to be initialized with same cookies as GeminiClient." 137 | ) 138 | return v 139 | 140 | # @override 141 | async def save( 142 | self, 143 | path: str = "temp", 144 | filename: str | None = None, 145 | cookies: dict | None = None, 146 | verbose: bool = False, 147 | skip_invalid_filename: bool = False, 148 | full_size: bool = True, 149 | ) -> str | None: 150 | """ 151 | Save the image to disk. 152 | 153 | Parameters 154 | ---------- 155 | path: `str`, optional 156 | Path to save the image, by default will save to "./temp". 157 | filename: `str`, optional 158 | Filename to save the image, generated images are always in .png format, but file extension will not be included in the URL. 159 | And since the URL ends with a long hash, by default will use timestamp + end of the hash as the filename. 160 | cookies: `dict`, optional 161 | Cookies used for requesting the content of the image. If not provided, will use the cookies from the GeneratedImage instance. 162 | verbose : `bool`, optional 163 | If True, will print the path of the saved file or warning for invalid file name, by default False. 164 | skip_invalid_filename: `bool`, optional 165 | If True, will only save the image if the file name and extension are valid, by default False. 166 | full_size: `bool`, optional 167 | If True, will modify the default preview (512*512) URL to get the full size image, by default True. 168 | 169 | Returns 170 | ------- 171 | `str | None` 172 | Absolute path of the saved image if successfully saved. 173 | """ 174 | 175 | if full_size: 176 | self.url += "=s2048" 177 | 178 | return await super().save( 179 | path=path, 180 | filename=filename 181 | or f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{self.url[-10:]}.png", 182 | cookies=cookies or self.cookies, 183 | verbose=verbose, 184 | skip_invalid_filename=skip_invalid_filename, 185 | ) 186 | -------------------------------------------------------------------------------- /tests/test_client_features.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | import logging 4 | from pathlib import Path 5 | 6 | from gemini_webapi import GeminiClient, Gem, set_log_level, logger 7 | from gemini_webapi.constants import Model 8 | from gemini_webapi.exceptions import AuthError, UsageLimitExceeded, ModelInvalid 9 | 10 | logging.getLogger("asyncio").setLevel(logging.ERROR) 11 | set_log_level("DEBUG") 12 | 13 | 14 | class TestGeminiClient(unittest.IsolatedAsyncioTestCase): 15 | async def asyncSetUp(self): 16 | self.geminiclient = GeminiClient( 17 | os.getenv("SECURE_1PSID"), os.getenv("SECURE_1PSIDTS"), verify=False 18 | ) 19 | 20 | try: 21 | await self.geminiclient.init(auto_refresh=False) 22 | except AuthError as e: 23 | self.skipTest(e) 24 | 25 | @logger.catch(reraise=True) 26 | async def test_successful_request(self): 27 | response = await self.geminiclient.generate_content( 28 | "Tell me a fact about today in history and illustrate it with a youtube video", 29 | model=Model.G_2_5_FLASH, 30 | ) 31 | logger.debug(response.text) 32 | 33 | @logger.catch(reraise=True) 34 | async def test_switch_model(self): 35 | for model in Model: 36 | if model.advanced_only: 37 | logger.debug(f"Model {model.model_name} requires an advanced account") 38 | continue 39 | 40 | try: 41 | response = await self.geminiclient.generate_content( 42 | "What's you language model version? Reply version number only.", 43 | model=model, 44 | ) 45 | logger.debug(f"Model version ({model.model_name}): {response.text}") 46 | except UsageLimitExceeded: 47 | logger.debug(f"Model {model.model_name} usage limit exceeded") 48 | except ModelInvalid: 49 | logger.debug(f"Model {model.model_name} is not available anymore") 50 | 51 | @logger.catch(reraise=True) 52 | async def test_upload_files(self): 53 | response = await self.geminiclient.generate_content( 54 | "Introduce the contents of these two files. Is there any connection between them?", 55 | files=["assets/sample.pdf", Path("assets/banner.png")], 56 | ) 57 | logger.debug(response.text) 58 | 59 | @logger.catch(reraise=True) 60 | async def test_continuous_conversation(self): 61 | chat = self.geminiclient.start_chat() 62 | response1 = await chat.send_message("Briefly introduce Europe") 63 | logger.debug(response1.text) 64 | response2 = await chat.send_message("What's the population there?") 65 | logger.debug(response2.text) 66 | 67 | @logger.catch(reraise=True) 68 | async def test_send_web_image(self): 69 | response = await self.geminiclient.generate_content( 70 | "Send me some pictures of cats" 71 | ) 72 | self.assertTrue(response.images) 73 | logger.debug(response.text) 74 | for image in response.images: 75 | logger.debug(image) 76 | 77 | @logger.catch(reraise=True) 78 | async def test_image_generation(self): 79 | response = await self.geminiclient.generate_content( 80 | "Generate some pictures of cats" 81 | ) 82 | self.assertTrue(response.images) 83 | logger.debug(response.text) 84 | for image in response.images: 85 | logger.debug(image) 86 | 87 | @logger.catch(reraise=True) 88 | async def test_image_to_image(self): 89 | response = await self.geminiclient.generate_content( 90 | "Design an application icon based on the provided image. Make it simple and modern.", 91 | files=["assets/banner.png"], 92 | ) 93 | self.assertTrue(response.images) 94 | logger.debug(response.text) 95 | for image in response.images: 96 | logger.debug(image) 97 | 98 | @logger.catch(reraise=True) 99 | async def test_generation_with_gem(self): 100 | response = await self.geminiclient.generate_content( 101 | "What's your system prompt?", 102 | model=Model.G_2_5_FLASH, 103 | gem=Gem(id="coding-partner", name="Coding partner", predefined=True), 104 | ) 105 | logger.debug(response.text) 106 | 107 | @logger.catch(reraise=True) 108 | async def test_thinking_model(self): 109 | response = await self.geminiclient.generate_content( 110 | "1+1=?", 111 | model=Model.G_2_5_PRO, 112 | ) 113 | logger.debug(response.thoughts) 114 | logger.debug(response.text) 115 | 116 | @logger.catch(reraise=True) 117 | async def test_retrieve_previous_conversation(self): 118 | chat = self.geminiclient.start_chat() 119 | await chat.send_message("Fine weather today") 120 | self.assertTrue(len(chat.metadata) == 3) 121 | previous_session = chat.metadata 122 | logger.debug(previous_session) 123 | previous_chat = self.geminiclient.start_chat(metadata=previous_session) 124 | response = await previous_chat.send_message("What was my previous message?") 125 | logger.debug(response) 126 | 127 | @logger.catch(reraise=True) 128 | async def test_chatsession_with_image(self): 129 | chat = self.geminiclient.start_chat() 130 | response1 = await chat.send_message( 131 | "What's the difference between these two images?", 132 | files=["assets/banner.png", "assets/favicon.png"], 133 | ) 134 | logger.debug(response1.text) 135 | response2 = await chat.send_message( 136 | "Use image generation tool to modify the banner with another font and design." 137 | ) 138 | logger.debug(response2.text) 139 | logger.debug(response2.images) 140 | 141 | @logger.catch(reraise=True) 142 | async def test_card_content(self): 143 | response = await self.geminiclient.generate_content("How is today's weather?") 144 | logger.debug(response.text) 145 | 146 | @logger.catch(reraise=True) 147 | async def test_extension_google_workspace(self): 148 | response = await self.geminiclient.generate_content( 149 | "@Gmail What's the latest message in my mailbox?" 150 | ) 151 | logger.debug(response) 152 | 153 | @logger.catch(reraise=True) 154 | async def test_extension_youtube(self): 155 | response = await self.geminiclient.generate_content( 156 | "@Youtube What's the latest activity of Taylor Swift?" 157 | ) 158 | logger.debug(response) 159 | 160 | @logger.catch(reraise=True) 161 | async def test_reply_candidates(self): 162 | chat = self.geminiclient.start_chat() 163 | response = await chat.send_message("Recommend a science fiction book for me.") 164 | 165 | if len(response.candidates) == 1: 166 | logger.debug(response.candidates[0]) 167 | self.skipTest("Only one candidate was returned. Test skipped") 168 | 169 | for candidate in response.candidates: 170 | logger.debug(candidate) 171 | 172 | new_candidate = chat.choose_candidate(index=1) 173 | self.assertEqual(response.chosen, 1) 174 | followup_response = await chat.send_message("Tell me more about it.") 175 | logger.warning(new_candidate.text) 176 | logger.warning(followup_response.text) 177 | 178 | 179 | if __name__ == "__main__": 180 | unittest.main() 181 | -------------------------------------------------------------------------------- /src/gemini_webapi/utils/get_access_token.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import asyncio 4 | from asyncio import Task 5 | from pathlib import Path 6 | 7 | from httpx import AsyncClient, Response 8 | 9 | from ..constants import Endpoint, Headers 10 | from ..exceptions import AuthError 11 | from .load_browser_cookies import load_browser_cookies 12 | from .logger import logger 13 | 14 | 15 | async def send_request( 16 | cookies: dict, proxy: str | None = None 17 | ) -> tuple[Response | None, dict]: 18 | """ 19 | Send http request with provided cookies. 20 | """ 21 | 22 | async with AsyncClient( 23 | proxy=proxy, 24 | headers=Headers.GEMINI.value, 25 | cookies=cookies, 26 | follow_redirects=True, 27 | verify=False, 28 | ) as client: 29 | response = await client.get(Endpoint.INIT.value) 30 | response.raise_for_status() 31 | return response, cookies 32 | 33 | 34 | async def get_access_token( 35 | base_cookies: dict, proxy: str | None = None, verbose: bool = False 36 | ) -> tuple[str, dict]: 37 | """ 38 | Send a get request to gemini.google.com for each group of available cookies and return 39 | the value of "SNlM0e" as access token on the first successful request. 40 | 41 | Possible cookie sources: 42 | - Base cookies passed to the function. 43 | - __Secure-1PSID from base cookies with __Secure-1PSIDTS from cache. 44 | - Local browser cookies (if optional dependency `browser-cookie3` is installed). 45 | 46 | Parameters 47 | ---------- 48 | base_cookies : `dict` 49 | Base cookies to be used in the request. 50 | proxy: `str`, optional 51 | Proxy URL. 52 | verbose: `bool`, optional 53 | If `True`, will print more infomation in logs. 54 | 55 | Returns 56 | ------- 57 | `str` 58 | Access token. 59 | `dict` 60 | Cookies of the successful request. 61 | 62 | Raises 63 | ------ 64 | `gemini_webapi.AuthError` 65 | If all requests failed. 66 | """ 67 | 68 | async with AsyncClient(proxy=proxy, follow_redirects=True, verify=False) as client: 69 | response = await client.get(Endpoint.GOOGLE.value) 70 | 71 | extra_cookies = {} 72 | if response.status_code == 200: 73 | extra_cookies = response.cookies 74 | 75 | tasks = [] 76 | 77 | # Base cookies passed directly on initializing client 78 | if "__Secure-1PSID" in base_cookies and "__Secure-1PSIDTS" in base_cookies: 79 | tasks.append(Task(send_request({**extra_cookies, **base_cookies}, proxy=proxy))) 80 | elif verbose: 81 | logger.debug( 82 | "Skipping loading base cookies. Either __Secure-1PSID or __Secure-1PSIDTS is not provided." 83 | ) 84 | 85 | # Cached cookies in local file 86 | cache_dir = ( 87 | (GEMINI_COOKIE_PATH := os.getenv("GEMINI_COOKIE_PATH")) 88 | and Path(GEMINI_COOKIE_PATH) 89 | or (Path(__file__).parent / "temp") 90 | ) 91 | if "__Secure-1PSID" in base_cookies: 92 | filename = f".cached_1psidts_{base_cookies['__Secure-1PSID']}.txt" 93 | cache_file = cache_dir / filename 94 | if cache_file.is_file(): 95 | cached_1psidts = cache_file.read_text() 96 | if cached_1psidts: 97 | cached_cookies = { 98 | **extra_cookies, 99 | **base_cookies, 100 | "__Secure-1PSIDTS": cached_1psidts, 101 | } 102 | tasks.append(Task(send_request(cached_cookies, proxy=proxy))) 103 | elif verbose: 104 | logger.debug("Skipping loading cached cookies. Cache file is empty.") 105 | elif verbose: 106 | logger.debug("Skipping loading cached cookies. Cache file not found.") 107 | else: 108 | valid_caches = 0 109 | cache_files = cache_dir.glob(".cached_1psidts_*.txt") 110 | for cache_file in cache_files: 111 | cached_1psidts = cache_file.read_text() 112 | if cached_1psidts: 113 | cached_cookies = { 114 | **extra_cookies, 115 | "__Secure-1PSID": cache_file.stem[16:], 116 | "__Secure-1PSIDTS": cached_1psidts, 117 | } 118 | tasks.append(Task(send_request(cached_cookies, proxy=proxy))) 119 | valid_caches += 1 120 | 121 | if valid_caches == 0 and verbose: 122 | logger.debug( 123 | "Skipping loading cached cookies. Cookies will be cached after successful initialization." 124 | ) 125 | 126 | # Browser cookies (if browser-cookie3 is installed) 127 | try: 128 | valid_browser_cookies = 0 129 | browser_cookies = load_browser_cookies( 130 | domain_name="google.com", verbose=verbose 131 | ) 132 | if browser_cookies: 133 | for browser, cookies in browser_cookies.items(): 134 | if secure_1psid := cookies.get("__Secure-1PSID"): 135 | if ( 136 | "__Secure-1PSID" in base_cookies 137 | and base_cookies["__Secure-1PSID"] != secure_1psid 138 | ): 139 | if verbose: 140 | logger.debug( 141 | f"Skipping loading local browser cookies from {browser}. " 142 | f"__Secure-1PSID does not match the one provided." 143 | ) 144 | continue 145 | 146 | local_cookies = {"__Secure-1PSID": secure_1psid} 147 | if secure_1psidts := cookies.get("__Secure-1PSIDTS"): 148 | local_cookies["__Secure-1PSIDTS"] = secure_1psidts 149 | if nid := cookies.get("NID"): 150 | local_cookies["NID"] = nid 151 | tasks.append(Task(send_request(local_cookies, proxy=proxy))) 152 | valid_browser_cookies += 1 153 | if verbose: 154 | logger.debug(f"Loaded local browser cookies from {browser}") 155 | 156 | if valid_browser_cookies == 0 and verbose: 157 | logger.debug( 158 | "Skipping loading local browser cookies. Login to gemini.google.com in your browser first." 159 | ) 160 | except ImportError: 161 | if verbose: 162 | logger.debug( 163 | "Skipping loading local browser cookies. Optional dependency 'browser-cookie3' is not installed." 164 | ) 165 | except Exception as e: 166 | if verbose: 167 | logger.warning(f"Skipping loading local browser cookies. {e}") 168 | 169 | if not tasks: 170 | raise AuthError( 171 | "No valid cookies available for initialization. Please pass __Secure-1PSID and __Secure-1PSIDTS manually." 172 | ) 173 | 174 | for i, future in enumerate(asyncio.as_completed(tasks)): 175 | try: 176 | response, request_cookies = await future 177 | match = re.search(r'"SNlM0e":"(.*?)"', response.text) 178 | if match: 179 | if verbose: 180 | logger.debug( 181 | f"Init attempt ({i + 1}/{len(tasks)}) succeeded. Initializing client..." 182 | ) 183 | return match.group(1), request_cookies 184 | elif verbose: 185 | logger.debug( 186 | f"Init attempt ({i + 1}/{len(tasks)}) failed. Cookies invalid." 187 | ) 188 | except Exception as e: 189 | if verbose: 190 | logger.debug( 191 | f"Init attempt ({i + 1}/{len(tasks)}) failed with error: {e}" 192 | ) 193 | 194 | raise AuthError( 195 | "Failed to initialize client. SECURE_1PSIDTS could get expired frequently, please make sure cookie values are up to date. " 196 | f"(Failed initialization attempts: {len(tasks)})" 197 | ) 198 | -------------------------------------------------------------------------------- /src/gemini_webapi/components/gem_mixin.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | import orjson as json 4 | 5 | from ..constants import GRPC 6 | from ..exceptions import APIError 7 | from ..types import Gem, GemJar, RPCData 8 | from ..utils import running, logger 9 | 10 | 11 | class GemMixin: 12 | """ 13 | Mixin class providing gem-related functionality for GeminiClient. 14 | """ 15 | 16 | def __init__(self, *args, **kwargs): 17 | super().__init__(*args, **kwargs) 18 | self._gems: GemJar | None = None 19 | 20 | @property 21 | def gems(self) -> GemJar: 22 | """ 23 | Returns a `GemJar` object containing cached gems. 24 | Only available after calling `GeminiClient.fetch_gems()`. 25 | 26 | Returns 27 | ------- 28 | :class:`GemJar` 29 | Refer to `gemini_webapi.types.GemJar`. 30 | 31 | Raises 32 | ------ 33 | `RuntimeError` 34 | If `GeminiClient.fetch_gems()` has not been called before accessing this property. 35 | """ 36 | 37 | if self._gems is None: 38 | raise RuntimeError( 39 | "Gems not fetched yet. Call `GeminiClient.fetch_gems()` method to fetch gems from gemini.google.com." 40 | ) 41 | 42 | return self._gems 43 | 44 | @running(retry=2) 45 | async def fetch_gems(self, include_hidden: bool = False, **kwargs) -> GemJar: 46 | """ 47 | Get a list of available gems from gemini, including system predefined gems and user-created custom gems. 48 | 49 | Note that network request will be sent every time this method is called. 50 | Once the gems are fetched, they will be cached and accessible via `GeminiClient.gems` property. 51 | 52 | Parameters 53 | ---------- 54 | include_hidden: `bool`, optional 55 | There are some predefined gems that by default are not shown to users (and therefore may not work properly). 56 | Set this parameter to `True` to include them in the fetched gem list. 57 | 58 | Returns 59 | ------- 60 | :class:`GemJar` 61 | Refer to `gemini_webapi.types.GemJar`. 62 | """ 63 | 64 | response = await self._batch_execute( 65 | [ 66 | RPCData( 67 | rpcid=GRPC.LIST_GEMS, 68 | payload="[4]" if include_hidden else "[3]", 69 | identifier="system", 70 | ), 71 | RPCData( 72 | rpcid=GRPC.LIST_GEMS, 73 | payload="[2]", 74 | identifier="custom", 75 | ), 76 | ], 77 | **kwargs, 78 | ) 79 | 80 | try: 81 | response_json = json.loads(response.text.split("\n")[2]) 82 | 83 | predefined_gems, custom_gems = [], [] 84 | 85 | for part in response_json: 86 | if part[-1] == "system": 87 | predefined_gems = json.loads(part[2])[2] 88 | elif part[-1] == "custom": 89 | if custom_gems_container := json.loads(part[2]): 90 | custom_gems = custom_gems_container[2] 91 | 92 | if not predefined_gems and not custom_gems: 93 | raise Exception 94 | except Exception: 95 | await self.close() 96 | logger.debug(f"Invalid response: {response.text}") 97 | raise APIError( 98 | "Failed to fetch gems. Invalid response data received. Client will try to re-initialize on next request." 99 | ) 100 | 101 | self._gems = GemJar( 102 | itertools.chain( 103 | ( 104 | ( 105 | gem[0], 106 | Gem( 107 | id=gem[0], 108 | name=gem[1][0], 109 | description=gem[1][1], 110 | prompt=gem[2] and gem[2][0] or None, 111 | predefined=True, 112 | ), 113 | ) 114 | for gem in predefined_gems 115 | ), 116 | ( 117 | ( 118 | gem[0], 119 | Gem( 120 | id=gem[0], 121 | name=gem[1][0], 122 | description=gem[1][1], 123 | prompt=gem[2] and gem[2][0] or None, 124 | predefined=False, 125 | ), 126 | ) 127 | for gem in custom_gems 128 | ), 129 | ) 130 | ) 131 | 132 | return self._gems 133 | 134 | @running(retry=2) 135 | async def create_gem(self, name: str, prompt: str, description: str = "") -> Gem: 136 | """ 137 | Create a new custom gem. 138 | 139 | Parameters 140 | ---------- 141 | name: `str` 142 | Name of the custom gem. 143 | prompt: `str` 144 | System instructions for the custom gem. 145 | description: `str`, optional 146 | Description of the custom gem (has no effect on the model's behavior). 147 | 148 | Returns 149 | ------- 150 | :class:`Gem` 151 | The created gem. 152 | """ 153 | 154 | response = await self._batch_execute( 155 | [ 156 | RPCData( 157 | rpcid=GRPC.CREATE_GEM, 158 | payload=json.dumps( 159 | [ 160 | [ 161 | name, 162 | description, 163 | prompt, 164 | None, 165 | None, 166 | None, 167 | None, 168 | None, 169 | 0, 170 | None, 171 | 1, 172 | None, 173 | None, 174 | None, 175 | [], 176 | ] 177 | ] 178 | ).decode(), 179 | ) 180 | ] 181 | ) 182 | 183 | try: 184 | response_json = json.loads(response.text.split("\n")[2]) 185 | gem_id = json.loads(response_json[0][2])[0] 186 | except Exception: 187 | await self.close() 188 | logger.debug(f"Invalid response: {response.text}") 189 | raise APIError( 190 | "Failed to create gem. Invalid response data received. Client will try to re-initialize on next request." 191 | ) 192 | 193 | return Gem( 194 | id=gem_id, 195 | name=name, 196 | description=description, 197 | prompt=prompt, 198 | predefined=False, 199 | ) 200 | 201 | @running(retry=2) 202 | async def update_gem( 203 | self, gem: Gem | str, name: str, prompt: str, description: str = "" 204 | ) -> Gem: 205 | """ 206 | Update an existing custom gem. 207 | 208 | Parameters 209 | ---------- 210 | gem: `Gem | str` 211 | Gem to update, can be either a `gemini_webapi.types.Gem` object or a gem id string. 212 | name: `str` 213 | New name for the custom gem. 214 | prompt: `str` 215 | New system instructions for the custom gem. 216 | description: `str`, optional 217 | New description of the custom gem (has no effect on the model's behavior). 218 | 219 | Returns 220 | ------- 221 | :class:`Gem` 222 | The updated gem. 223 | """ 224 | 225 | if isinstance(gem, Gem): 226 | gem_id = gem.id 227 | else: 228 | gem_id = gem 229 | 230 | await self._batch_execute( 231 | [ 232 | RPCData( 233 | rpcid=GRPC.UPDATE_GEM, 234 | payload=json.dumps( 235 | [ 236 | gem_id, 237 | [ 238 | name, 239 | description, 240 | prompt, 241 | None, 242 | None, 243 | None, 244 | None, 245 | None, 246 | 0, 247 | None, 248 | 1, 249 | None, 250 | None, 251 | None, 252 | [], 253 | 0, 254 | ], 255 | ] 256 | ).decode(), 257 | ) 258 | ] 259 | ) 260 | 261 | return Gem( 262 | id=gem_id, 263 | name=name, 264 | description=description, 265 | prompt=prompt, 266 | predefined=False, 267 | ) 268 | 269 | @running(retry=2) 270 | async def delete_gem(self, gem: Gem | str, **kwargs) -> None: 271 | """ 272 | Delete a custom gem. 273 | 274 | Parameters 275 | ---------- 276 | gem: `Gem | str` 277 | Gem to delete, can be either a `gemini_webapi.types.Gem` object or a gem id string. 278 | """ 279 | 280 | if isinstance(gem, Gem): 281 | gem_id = gem.id 282 | else: 283 | gem_id = gem 284 | 285 | await self._batch_execute( 286 | [RPCData(rpcid=GRPC.DELETE_GEM, payload=json.dumps([gem_id]).decode())], 287 | **kwargs, 288 | ) 289 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Gemini Banner 3 |

4 |

5 | 6 | PyPI 7 | 8 | Downloads 9 | 10 | Dependencies 11 | 12 | License 13 | 14 | Code style 15 |

16 |

17 | 18 | GitHub stars 19 | 20 | GitHub issues 21 | 22 | CI 23 |

24 | 25 | # Gemini Icon Gemini-API 26 | 27 | A reverse-engineered asynchronous python wrapper for [Google Gemini](https://gemini.google.com) web app (formerly Bard). 28 | 29 | ## Features 30 | 31 | - **Persistent Cookies** - Automatically refreshes cookies in background. Optimized for always-on services. 32 | - **Image Generation** - Natively supports generating and editing images with natural language. 33 | - **System Prompt** - Supports customizing model's system prompt with [Gemini Gems](https://gemini.google.com/gems/view). 34 | - **Extension Support** - Supports generating contents with [Gemini extensions](https://gemini.google.com/extensions) on, like YouTube and Gmail. 35 | - **Classified Outputs** - Categorizes texts, thoughts, web images and AI generated images in the response. 36 | - **Official Flavor** - Provides a simple and elegant interface inspired by [Google Generative AI](https://ai.google.dev/tutorials/python_quickstart)'s official API. 37 | - **Asynchronous** - Utilizes `asyncio` to run generating tasks and return outputs efficiently. 38 | 39 | ## Table of Contents 40 | 41 | - [Features](#features) 42 | - [Table of Contents](#table-of-contents) 43 | - [Installation](#installation) 44 | - [Authentication](#authentication) 45 | - [Usage](#usage) 46 | - [Initialization](#initialization) 47 | - [Generate contents](#generate-contents) 48 | - [Generate contents with files](#generate-contents-with-files) 49 | - [Conversations across multiple turns](#conversations-across-multiple-turns) 50 | - [Continue previous conversations](#continue-previous-conversations) 51 | - [Select language model](#select-language-model) 52 | - [Apply system prompt with Gemini Gems](#apply-system-prompt-with-gemini-gems) 53 | - [Manage Custom Gems](#manage-custom-gems) 54 | - [Create a custom gem](#create-a-custom-gem) 55 | - [Update an existing gem](#update-an-existing-gem) 56 | - [Delete a custom gem](#delete-a-custom-gem) 57 | - [Retrieve model's thought process](#retrieve-models-thought-process) 58 | - [Retrieve images in response](#retrieve-images-in-response) 59 | - [Generate and edit images](#generate-and-edit-images) 60 | - [Generate contents with Gemini extensions](#generate-contents-with-gemini-extensions) 61 | - [Check and switch to other reply candidates](#check-and-switch-to-other-reply-candidates) 62 | - [Logging Configuration](#logging-configuration) 63 | - [References](#references) 64 | - [Stargazers](#stargazers) 65 | 66 | ## Installation 67 | 68 | > [!NOTE] 69 | > 70 | > This package requires Python 3.10 or higher. 71 | 72 | Install/update the package with pip. 73 | 74 | ```sh 75 | pip install -U gemini_webapi 76 | ``` 77 | 78 | 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](https://github.com/borisbabic/browser_cookie3?tab=readme-ov-file#contribute). 79 | 80 | ```sh 81 | pip install -U browser-cookie3 82 | ``` 83 | 84 | ## Authentication 85 | 86 | > [!TIP] 87 | > 88 | > If `browser-cookie3` is installed, you can skip this step and go directly to [usage](#usage) section. Just make sure you have logged in to in your browser. 89 | 90 | - Go to and login with your Google account 91 | - Press F12 for web inspector, go to `Network` tab and refresh the page 92 | - Click any request and copy cookie values of `__Secure-1PSID` and `__Secure-1PSIDTS` 93 | 94 | > [!NOTE] 95 | > 96 | > 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_PATH` environment variable to specify the path where auto-refreshed cookies are stored. Make sure the path is writable by the application. 97 | > 98 | > Here's part of a sample `docker-compose.yml` file: 99 | 100 | ```yaml 101 | services: 102 | main: 103 | environment: 104 | GEMINI_COOKIE_PATH: /tmp/gemini_webapi 105 | volumes: 106 | - ./gemini_cookies:/tmp/gemini_webapi 107 | ``` 108 | 109 | > [!NOTE] 110 | > 111 | > API's auto cookie refreshing feature doesn't require `browser-cookie3`, and by default is enabled. It allows you to keep the API service running without worrying about cookie expiration. 112 | > 113 | > This feature may cause that you need to re-login to your Google account in the browser. This is an expected behavior and won't affect the API's functionality. 114 | > 115 | > To avoid such result, it's recommended to get cookies from a separate browser session and close it as asap for best utilization (e.g. a fresh login in browser's private mode). More details can be found [here](https://github.com/HanaokaYuzu/Gemini-API/issues/6). 116 | 117 | ## Usage 118 | 119 | ### Initialization 120 | 121 | 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. 122 | 123 | ```python 124 | import asyncio 125 | from gemini_webapi import GeminiClient 126 | 127 | # Replace "COOKIE VALUE HERE" with your actual cookie values. 128 | # Leave Secure_1PSIDTS empty if it's not available for your account. 129 | Secure_1PSID = "COOKIE VALUE HERE" 130 | Secure_1PSIDTS = "COOKIE VALUE HERE" 131 | 132 | async def main(): 133 | # If browser-cookie3 is installed, simply use `client = GeminiClient()` 134 | client = GeminiClient(Secure_1PSID, Secure_1PSIDTS, proxy=None) 135 | await client.init(timeout=30, auto_close=False, close_delay=300, auto_refresh=True) 136 | 137 | asyncio.run(main()) 138 | ``` 139 | 140 | > [!TIP] 141 | > 142 | > `auto_close` and `close_delay` are 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 chatbot, it's recommended to set `auto_close` to `True` combined with reasonable seconds of `close_delay` for better resource management. 143 | 144 | ### Generate contents 145 | 146 | 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. 147 | 148 | ```python 149 | async def main(): 150 | response = await client.generate_content("Hello World!") 151 | print(response.text) 152 | 153 | asyncio.run(main()) 154 | ``` 155 | 156 | > [!TIP] 157 | > 158 | > Simply use `print(response)` to get the same output if you just want to see the response text 159 | 160 | ### Generate contents with files 161 | 162 | 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. 163 | 164 | ```python 165 | async def main(): 166 | response = await client.generate_content( 167 | "Introduce the contents of these two files. Is there any connection between them?", 168 | files=["assets/sample.pdf", Path("assets/banner.png")], 169 | ) 170 | print(response.text) 171 | 172 | asyncio.run(main()) 173 | ``` 174 | 175 | ### Conversations across multiple turns 176 | 177 | If you want to keep conversation continuous, please use `GeminiClient.start_chat` to create a `gemini_webapi.ChatSession` object and send messages through it. The conversation history will be automatically handled and get updated after each turn. 178 | 179 | ```python 180 | async def main(): 181 | chat = client.start_chat() 182 | response1 = await chat.send_message( 183 | "Introduce the contents of these two files. Is there any connection between them?", 184 | files=["assets/sample.pdf", Path("assets/banner.png")], 185 | ) 186 | print(response1.text) 187 | response2 = await chat.send_message( 188 | "Use image generation tool to modify the banner with another font and design." 189 | ) 190 | print(response2.text, response2.images, sep="\n\n----------------------------------\n\n") 191 | 192 | asyncio.run(main()) 193 | ``` 194 | 195 | > [!TIP] 196 | > 197 | > Same as `GeminiClient.generate_content`, `ChatSession.send_message` also accepts `image` as an optional argument. 198 | 199 | ### Continue previous conversations 200 | 201 | 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. 202 | 203 | ```python 204 | async def main(): 205 | # Start a new chat session 206 | chat = client.start_chat() 207 | response = await chat.send_message("Fine weather today") 208 | 209 | # Save chat's metadata 210 | previous_session = chat.metadata 211 | 212 | # Load the previous conversation 213 | previous_chat = client.start_chat(metadata=previous_session) 214 | response = await previous_chat.send_message("What was my previous message?") 215 | print(response) 216 | 217 | asyncio.run(main()) 218 | ``` 219 | 220 | ### Select language model 221 | 222 | 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`. 223 | 224 | Currently available models (as of November 20, 2025): 225 | 226 | - `unspecified` - Default model 227 | - `gemini-3.0-pro` - Gemini 3.0 Pro 228 | - `gemini-2.5-pro` - Gemini 2.5 Pro 229 | - `gemini-2.5-flash` - Gemini 2.5 Flash 230 | 231 | ```python 232 | from gemini_webapi.constants import Model 233 | 234 | async def main(): 235 | response1 = await client.generate_content( 236 | "What's you language model version? Reply version number only.", 237 | model=Model.G_2_5_FLASH, 238 | ) 239 | print(f"Model version ({Model.G_2_5_FLASH.model_name}): {response1.text}") 240 | 241 | chat = client.start_chat(model="gemini-2.5-pro") 242 | response2 = await chat.send_message("What's you language model version? Reply version number only.") 243 | print(f"Model version (gemini-2.5-pro): {response2.text}") 244 | 245 | asyncio.run(main()) 246 | ``` 247 | 248 | You can also pass custom model header strings directly to access models which are not listed above. 249 | 250 | ```python 251 | # "model_name" and "model_header" keys must be present 252 | custom_model = { 253 | "model_name": "xxx", 254 | "model_header": { 255 | "x-goog-ext-525001261-jspb": "[1,null,null,null,'e6fa609c3fa255c0',null,null,null,[4]]" 256 | }, 257 | } 258 | 259 | response = await client.generate_content( 260 | "What's your model version?", 261 | model=custom_model 262 | ) 263 | ``` 264 | 265 | ### Apply system prompt with Gemini Gems 266 | 267 | System prompt can be applied to conversations via [Gemini Gems](https://gemini.google.com/gems/view). To use a gem, you can pass `gem` argument to `GeminiClient.generate_content` or `GeminiClient.start_chat`. `gem` can be either a string of gem id or a `gemini_webapi.Gem` object. Only one gem can be applied to a single conversation. 268 | 269 | > [!TIP] 270 | > 271 | > There are some system predefined gems that by default are not shown to users (and therefore may not work properly). Use `client.fetch_gems(include_hidden=True)` to include them in the fetch result. 272 | 273 | ```python 274 | async def main(): 275 | # Fetch all gems for the current account, including both predefined and user-created ones 276 | await client.fetch_gems(include_hidden=False) 277 | 278 | # Once fetched, gems will be cached in `GeminiClient.gems` 279 | gems = client.gems 280 | 281 | # Get the gem you want to use 282 | system_gems = gems.filter(predefined=True) 283 | coding_partner = system_gems.get(id="coding-partner") 284 | 285 | response1 = await client.generate_content( 286 | "what's your system prompt?", 287 | model=Model.G_2_5_FLASH, 288 | gem=coding_partner, 289 | ) 290 | print(response1.text) 291 | 292 | # Another example with a user-created custom gem 293 | # Gem ids are consistent strings. Store them somewhere to avoid fetching gems every time 294 | your_gem = gems.get(name="Your Gem Name") 295 | your_gem_id = your_gem.id 296 | chat = client.start_chat(gem=your_gem_id) 297 | response2 = await chat.send_message("what's your system prompt?") 298 | print(response2) 299 | ``` 300 | 301 | ### Manage Custom Gems 302 | 303 | You can create, update, and delete your custom gems programmatically with the API. Note that predefined system gems cannot be modified or deleted. 304 | 305 | #### Create a custom gem 306 | 307 | Create a new custom gem with a name, system prompt (instructions), and optional description: 308 | 309 | ```python 310 | async def main(): 311 | # Create a new custom gem 312 | new_gem = await client.create_gem( 313 | name="Python Tutor", 314 | prompt="You are a helpful Python programming tutor.", 315 | description="A specialized gem for Python programming" 316 | ) 317 | 318 | print(f"Custom gem created: {new_gem}") 319 | 320 | # Use the newly created gem in a conversation 321 | response = await client.generate_content( 322 | "Explain how list comprehensions work in Python", 323 | gem=new_gem 324 | ) 325 | print(response.text) 326 | 327 | asyncio.run(main()) 328 | ``` 329 | 330 | #### Update an existing gem 331 | 332 | > [!NOTE] 333 | > 334 | > When updating a gem, you must provide all parameters (name, prompt, description) even if you only want to change one of them. 335 | 336 | ```python 337 | async def main(): 338 | # Get a custom gem (assuming you have one named "Python Tutor") 339 | await client.fetch_gems() 340 | python_tutor = client.gems.get(name="Python Tutor") 341 | 342 | # Update the gem with new instructions 343 | updated_gem = await client.update_gem( 344 | gem=python_tutor, # Can also pass gem ID string 345 | name="Advanced Python Tutor", 346 | prompt="You are an expert Python programming tutor.", 347 | description="An advanced Python programming assistant" 348 | ) 349 | 350 | print(f"Custom gem updated: {updated_gem}") 351 | 352 | asyncio.run(main()) 353 | ``` 354 | 355 | #### Delete a custom gem 356 | 357 | ```python 358 | async def main(): 359 | # Get the gem to delete 360 | await client.fetch_gems() 361 | gem_to_delete = client.gems.get(name="Advanced Python Tutor") 362 | 363 | # Delete the gem 364 | await client.delete_gem(gem_to_delete) # Can also pass gem ID string 365 | print(f"Custom gem deleted: {gem_to_delete.name}") 366 | 367 | asyncio.run(main()) 368 | ``` 369 | 370 | ### Retrieve model's thought process 371 | 372 | When using models with thinking capabilities, the model's thought process will be populated in `ModelOutput.thoughts`. 373 | 374 | ```python 375 | async def main(): 376 | response = await client.generate_content( 377 | "What's 1+1?", model="gemini-2.5-pro" 378 | ) 379 | print(response.thoughts) 380 | print(response.text) 381 | 382 | asyncio.run(main()) 383 | ``` 384 | 385 | ### Retrieve images in response 386 | 387 | Images in the API's output are stored as a list of `gemini_webapi.Image` objects. You can access the image title, URL, and description by calling `Image.title`, `Image.url` and `Image.alt` respectively. 388 | 389 | ```python 390 | async def main(): 391 | response = await client.generate_content("Send me some pictures of cats") 392 | for image in response.images: 393 | print(image, "\n\n----------------------------------\n") 394 | 395 | asyncio.run(main()) 396 | ``` 397 | 398 | ### Generate and edit images 399 | 400 | You can ask Gemini to generate and edit images with Nano Banana, Google's latest image model, simply by natural language. 401 | 402 | > [!IMPORTANT] 403 | > 404 | > Google has some limitations on the image generation feature in Gemini, so its availability could be different per region/account. Here's a summary copied from [official documentation](https://support.google.com/gemini/answer/14286560) (as of Sep 10, 2025): 405 | > 406 | > > This feature’s availability in any specific Gemini app is also limited to the supported languages and countries of that app. 407 | > > 408 | > > For now, this feature isn’t available to users under 18. 409 | > > 410 | > > To use this feature, you must be signed in to Gemini Apps. 411 | 412 | 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`. 413 | 414 | ```python 415 | async def main(): 416 | response = await client.generate_content("Generate some pictures of cats") 417 | for i, image in enumerate(response.images): 418 | await image.save(path="temp/", filename=f"cat_{i}.png", verbose=True) 419 | print(image, "\n\n----------------------------------\n") 420 | 421 | asyncio.run(main()) 422 | ``` 423 | 424 | > [!NOTE] 425 | > 426 | > by default, when asked to send images (like the previous example), Gemini will send images fetched from web instead of generating images with AI model, unless you specifically require to "generate" images in your prompt. In this package, web images and generated images are treated differently as `WebImage` and `GeneratedImage`, and will be automatically categorized in the output. 427 | 428 | ### Generate contents with Gemini extensions 429 | 430 | > [!IMPORTANT] 431 | > 432 | > To access Gemini extensions in API, you must activate them on the [Gemini website](https://gemini.google.com/extensions) first. Same as image generation, Google also has limitations on the availability of Gemini extensions. Here's a summary copied from [official documentation](https://support.google.com/gemini/answer/13695044) (as of March 19th, 2025): 433 | > 434 | > > To connect apps to Gemini, you must have​​​​ Gemini Apps Activity on. 435 | > > 436 | > > To use this feature, you must be signed in to Gemini Apps. 437 | > > 438 | > > Important: If you’re under 18, Google Workspace and Maps apps currently only work with English prompts in Gemini. 439 | 440 | 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. 441 | 442 | ```python 443 | async def main(): 444 | response1 = await client.generate_content("@Gmail What's the latest message in my mailbox?") 445 | print(response1, "\n\n----------------------------------\n") 446 | 447 | response2 = await client.generate_content("@Youtube What's the latest activity of Taylor Swift?") 448 | print(response2, "\n\n----------------------------------\n") 449 | 450 | asyncio.run(main()) 451 | ``` 452 | 453 | > [!NOTE] 454 | > 455 | > For the available regions limitation, it actually only requires your Google account's **preferred language** to be set to one of the three supported languages listed above. You can change your language settings [here](https://myaccount.google.com/language). 456 | 457 | ### Check and switch to other reply candidates 458 | 459 | A response from Gemini sometimes 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. 460 | 461 | ```python 462 | async def main(): 463 | # Start a conversation and list all reply candidates 464 | chat = client.start_chat() 465 | response = await chat.send_message("Recommend a science fiction book for me.") 466 | for candidate in response.candidates: 467 | print(candidate, "\n\n----------------------------------\n") 468 | 469 | if len(response.candidates) > 1: 470 | # Control the ongoing conversation flow by choosing candidate manually 471 | new_candidate = chat.choose_candidate(index=1) # Choose the second candidate here 472 | followup_response = await chat.send_message("Tell me more about it.") # Will generate contents based on the chosen candidate 473 | print(new_candidate, followup_response, sep="\n\n----------------------------------\n\n") 474 | else: 475 | print("Only one candidate available.") 476 | 477 | asyncio.run(main()) 478 | ``` 479 | 480 | ### Logging Configuration 481 | 482 | This package uses [loguru](https://loguru.readthedocs.io/en/stable/) for logging, and exposes a function `set_log_level` to control log level. You can set log level to one of the following values: `DEBUG`, `INFO`, `WARNING`, `ERROR` and `CRITICAL`. The default value is `INFO`. 483 | 484 | ```python 485 | from gemini_webapi import set_log_level 486 | 487 | set_log_level("DEBUG") 488 | ``` 489 | 490 | > [!NOTE] 491 | > 492 | > Calling `set_log_level` for the first time will **globally** remove all existing loguru handlers. You may want to configure logging directly with loguru to avoid this issue and have more advanced control over logging behaviors. 493 | 494 | ## References 495 | 496 | [Google AI Studio](https://ai.google.dev/tutorials/ai-studio_quickstart) 497 | 498 | [acheong08/Bard](https://github.com/acheong08/Bard) 499 | 500 | ## Stargazers 501 | 502 |

503 | 504 | Star History Chart 505 |

506 | -------------------------------------------------------------------------------- /src/gemini_webapi/client.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import re 3 | from asyncio import Task 4 | from pathlib import Path 5 | from typing import Any, Optional 6 | 7 | import orjson as json 8 | from httpx import AsyncClient, ReadTimeout, Response 9 | 10 | from .components import GemMixin 11 | from .constants import Endpoint, ErrorCode, Headers, Model 12 | from .exceptions import ( 13 | APIError, 14 | AuthError, 15 | GeminiError, 16 | ImageGenerationError, 17 | ModelInvalid, 18 | TemporarilyBlocked, 19 | TimeoutError, 20 | UsageLimitExceeded, 21 | ) 22 | from .types import ( 23 | Candidate, 24 | Gem, 25 | GeneratedImage, 26 | ModelOutput, 27 | RPCData, 28 | WebImage, 29 | ) 30 | from .utils import ( 31 | extract_json_from_response, 32 | get_access_token, 33 | get_nested_value, 34 | logger, 35 | parse_file_name, 36 | rotate_1psidts, 37 | rotate_tasks, 38 | running, 39 | upload_file, 40 | ) 41 | 42 | 43 | class GeminiClient(GemMixin): 44 | """ 45 | Async httpx client interface for gemini.google.com. 46 | 47 | `secure_1psid` must be provided unless the optional dependency `browser-cookie3` is installed, and 48 | you have logged in to google.com in your local browser. 49 | 50 | Parameters 51 | ---------- 52 | secure_1psid: `str`, optional 53 | __Secure-1PSID cookie value. 54 | secure_1psidts: `str`, optional 55 | __Secure-1PSIDTS cookie value, some google accounts don't require this value, provide only if it's in the cookie list. 56 | proxy: `str`, optional 57 | Proxy URL. 58 | kwargs: `dict`, optional 59 | Additional arguments which will be passed to the http client. 60 | Refer to `httpx.AsyncClient` for more information. 61 | 62 | Raises 63 | ------ 64 | `ValueError` 65 | If `browser-cookie3` is installed but cookies for google.com are not found in your local browser storage. 66 | """ 67 | 68 | __slots__ = [ 69 | "cookies", 70 | "proxy", 71 | "_running", 72 | "client", 73 | "access_token", 74 | "timeout", 75 | "auto_close", 76 | "close_delay", 77 | "close_task", 78 | "auto_refresh", 79 | "refresh_interval", 80 | "_gems", # From GemMixin 81 | "kwargs", 82 | ] 83 | 84 | def __init__( 85 | self, 86 | secure_1psid: str | None = None, 87 | secure_1psidts: str | None = None, 88 | proxy: str | None = None, 89 | **kwargs, 90 | ): 91 | super().__init__() 92 | self.cookies = {} 93 | self.proxy = proxy 94 | self._running: bool = False 95 | self.client: AsyncClient | None = None 96 | self.access_token: str | None = None 97 | self.timeout: float = 300 98 | self.auto_close: bool = False 99 | self.close_delay: float = 300 100 | self.close_task: Task | None = None 101 | self.auto_refresh: bool = True 102 | self.refresh_interval: float = 540 103 | self.kwargs = kwargs 104 | 105 | if secure_1psid: 106 | self.cookies["__Secure-1PSID"] = secure_1psid 107 | if secure_1psidts: 108 | self.cookies["__Secure-1PSIDTS"] = secure_1psidts 109 | 110 | async def init( 111 | self, 112 | timeout: float = 300, 113 | auto_close: bool = False, 114 | close_delay: float = 300, 115 | auto_refresh: bool = True, 116 | refresh_interval: float = 540, 117 | verbose: bool = True, 118 | ) -> None: 119 | """ 120 | Get SNlM0e value as access token. Without this token posting will fail with 400 bad request. 121 | 122 | Parameters 123 | ---------- 124 | timeout: `float`, optional 125 | Request timeout of the client in seconds. Used to limit the max waiting time when sending a request. 126 | auto_close: `bool`, optional 127 | If `True`, the client will close connections and clear resource usage after a certain period 128 | of inactivity. Useful for always-on services. 129 | close_delay: `float`, optional 130 | Time to wait before auto-closing the client in seconds. Effective only if `auto_close` is `True`. 131 | auto_refresh: `bool`, optional 132 | If `True`, will schedule a task to automatically refresh cookies in the background. 133 | refresh_interval: `float`, optional 134 | Time interval for background cookie refresh in seconds. Effective only if `auto_refresh` is `True`. 135 | verbose: `bool`, optional 136 | If `True`, will print more infomation in logs. 137 | """ 138 | 139 | try: 140 | access_token, valid_cookies = await get_access_token( 141 | base_cookies=self.cookies, proxy=self.proxy, verbose=verbose 142 | ) 143 | 144 | self.client = AsyncClient( 145 | timeout=timeout, 146 | proxy=self.proxy, 147 | follow_redirects=True, 148 | headers=Headers.GEMINI.value, 149 | cookies=valid_cookies, 150 | **self.kwargs, 151 | ) 152 | self.access_token = access_token 153 | self.cookies = valid_cookies 154 | self._running = True 155 | 156 | self.timeout = timeout 157 | self.auto_close = auto_close 158 | self.close_delay = close_delay 159 | if self.auto_close: 160 | await self.reset_close_task() 161 | 162 | self.auto_refresh = auto_refresh 163 | self.refresh_interval = refresh_interval 164 | if task := rotate_tasks.get(self.cookies["__Secure-1PSID"]): 165 | task.cancel() 166 | if self.auto_refresh: 167 | rotate_tasks[self.cookies["__Secure-1PSID"]] = asyncio.create_task( 168 | self.start_auto_refresh() 169 | ) 170 | 171 | if verbose: 172 | logger.success("Gemini client initialized successfully.") 173 | except Exception: 174 | await self.close() 175 | raise 176 | 177 | async def close(self, delay: float = 0) -> None: 178 | """ 179 | Close the client after a certain period of inactivity, or call manually to close immediately. 180 | 181 | Parameters 182 | ---------- 183 | delay: `float`, optional 184 | Time to wait before closing the client in seconds. 185 | """ 186 | 187 | if delay: 188 | await asyncio.sleep(delay) 189 | 190 | self._running = False 191 | 192 | if self.close_task: 193 | self.close_task.cancel() 194 | self.close_task = None 195 | 196 | if self.client: 197 | await self.client.aclose() 198 | 199 | async def reset_close_task(self) -> None: 200 | """ 201 | Reset the timer for closing the client when a new request is made. 202 | """ 203 | 204 | if self.close_task: 205 | self.close_task.cancel() 206 | self.close_task = None 207 | 208 | self.close_task = asyncio.create_task(self.close(self.close_delay)) 209 | 210 | async def start_auto_refresh(self) -> None: 211 | """ 212 | Start the background task to automatically refresh cookies. 213 | """ 214 | 215 | while True: 216 | new_1psidts: str | None = None 217 | try: 218 | new_1psidts = await rotate_1psidts(self.cookies, self.proxy) 219 | except AuthError: 220 | if task := rotate_tasks.get(self.cookies.get("__Secure-1PSID", "")): 221 | task.cancel() 222 | logger.warning( 223 | "AuthError: Failed to refresh cookies. Auto refresh task canceled." 224 | ) 225 | return 226 | except Exception as exc: 227 | logger.warning(f"Unexpected error while refreshing cookies: {exc}") 228 | 229 | if new_1psidts: 230 | self.cookies["__Secure-1PSIDTS"] = new_1psidts 231 | if self._running: 232 | self.client.cookies.set("__Secure-1PSIDTS", new_1psidts) 233 | logger.debug("Cookies refreshed. New __Secure-1PSIDTS applied.") 234 | 235 | await asyncio.sleep(self.refresh_interval) 236 | 237 | @running(retry=2) 238 | async def generate_content( 239 | self, 240 | prompt: str, 241 | files: list[str | Path] | None = None, 242 | model: Model | str | dict = Model.UNSPECIFIED, 243 | gem: Gem | str | None = None, 244 | chat: Optional["ChatSession"] = None, 245 | **kwargs, 246 | ) -> ModelOutput: 247 | """ 248 | Generates contents with prompt. 249 | 250 | Parameters 251 | ---------- 252 | prompt: `str` 253 | Prompt provided by user. 254 | files: `list[str | Path]`, optional 255 | List of file paths to be attached. 256 | model: `Model | str | dict`, optional 257 | Specify the model to use for generation. 258 | Pass either a `gemini_webapi.constants.Model` enum or a model name string to use predefined models. 259 | Pass a dictionary to use custom model header strings ("model_name" and "model_header" keys must be provided). 260 | gem: `Gem | str`, optional 261 | Specify a gem to use as system prompt for the chat session. 262 | Pass either a `gemini_webapi.types.Gem` object or a gem id string. 263 | chat: `ChatSession`, optional 264 | Chat data to retrieve conversation history. If None, will automatically generate a new chat id when sending post request. 265 | kwargs: `dict`, optional 266 | Additional arguments which will be passed to the post request. 267 | Refer to `httpx.AsyncClient.request` for more information. 268 | 269 | Returns 270 | ------- 271 | :class:`ModelOutput` 272 | Output data from gemini.google.com, use `ModelOutput.text` to get the default text reply, `ModelOutput.images` to get a list 273 | of images in the default reply, `ModelOutput.candidates` to get a list of all answer candidates in the output. 274 | 275 | Raises 276 | ------ 277 | `AssertionError` 278 | If prompt is empty. 279 | `gemini_webapi.TimeoutError` 280 | If request timed out. 281 | `gemini_webapi.GeminiError` 282 | If no reply candidate found in response. 283 | `gemini_webapi.APIError` 284 | - If request failed with status code other than 200. 285 | - If response structure is invalid and failed to parse. 286 | """ 287 | 288 | assert prompt, "Prompt cannot be empty." 289 | 290 | if isinstance(model, str): 291 | model = Model.from_name(model) 292 | elif isinstance(model, dict): 293 | model = Model.from_dict(model) 294 | elif not isinstance(model, Model): 295 | raise TypeError( 296 | f"'model' must be a `gemini_webapi.constants.Model` instance, " 297 | f"string, or dictionary; got `{type(model).__name__}`" 298 | ) 299 | 300 | if isinstance(gem, Gem): 301 | gem_id = gem.id 302 | else: 303 | gem_id = gem 304 | 305 | if self.auto_close: 306 | await self.reset_close_task() 307 | 308 | try: 309 | response = await self.client.post( 310 | Endpoint.GENERATE.value, 311 | headers=model.model_header, 312 | data={ 313 | "at": self.access_token, 314 | "f.req": json.dumps( 315 | [ 316 | None, 317 | json.dumps( 318 | [ 319 | files 320 | and [ 321 | prompt, 322 | 0, 323 | None, 324 | [ 325 | [ 326 | [await upload_file(file, self.proxy)], 327 | parse_file_name(file), 328 | ] 329 | for file in files 330 | ], 331 | ] 332 | or [prompt], 333 | None, 334 | chat and chat.metadata, 335 | ] 336 | + (gem_id and [None] * 16 + [gem_id] or []) 337 | ).decode(), 338 | ] 339 | ).decode(), 340 | }, 341 | **kwargs, 342 | ) 343 | except ReadTimeout: 344 | raise TimeoutError( 345 | "Generate content request timed out, please try again. If the problem persists, " 346 | "consider setting a higher `timeout` value when initializing GeminiClient." 347 | ) 348 | 349 | if response.status_code != 200: 350 | await self.close() 351 | raise APIError( 352 | f"Failed to generate contents. Request failed with status code {response.status_code}" 353 | ) 354 | else: 355 | response_json: list[Any] = [] 356 | body: list[Any] = [] 357 | body_index = 0 358 | 359 | try: 360 | response_json = extract_json_from_response(response.text) 361 | 362 | for part_index, part in enumerate(response_json): 363 | try: 364 | part_body = get_nested_value(part, [2]) 365 | if not part_body: 366 | continue 367 | 368 | part_json = json.loads(part_body) 369 | if get_nested_value(part_json, [4]): 370 | body_index, body = part_index, part_json 371 | break 372 | except json.JSONDecodeError: 373 | continue 374 | 375 | if not body: 376 | raise Exception 377 | except Exception: 378 | await self.close() 379 | 380 | try: 381 | error_code = get_nested_value(response_json, [0, 5, 2, 0, 1, 0], -1) 382 | match error_code: 383 | case ErrorCode.USAGE_LIMIT_EXCEEDED: 384 | raise UsageLimitExceeded( 385 | f"Failed to generate contents. Usage limit of {model.model_name} model has exceeded. Please try switching to another model." 386 | ) 387 | case ErrorCode.MODEL_INCONSISTENT: 388 | raise ModelInvalid( 389 | "Failed to generate contents. The specified model is inconsistent with the chat history. Please make sure to pass the same " 390 | "`model` parameter when starting a chat session with previous metadata." 391 | ) 392 | case ErrorCode.MODEL_HEADER_INVALID: 393 | raise ModelInvalid( 394 | "Failed to generate contents. The specified model is not available. Please update gemini_webapi to the latest version. " 395 | "If the error persists and is caused by the package, please report it on GitHub." 396 | ) 397 | case ErrorCode.IP_TEMPORARILY_BLOCKED: 398 | raise TemporarilyBlocked( 399 | "Failed to generate contents. Your IP address is temporarily blocked by Google. Please try using a proxy or waiting for a while." 400 | ) 401 | case _: 402 | raise Exception 403 | except GeminiError: 404 | raise 405 | except Exception: 406 | logger.debug(f"Invalid response: {response.text}") 407 | raise APIError( 408 | "Failed to generate contents. Invalid response data received. Client will try to re-initialize on next request." 409 | ) 410 | 411 | try: 412 | candidate_list: list[Any] = get_nested_value(body, [4], []) 413 | output_candidates: list[Candidate] = [] 414 | 415 | for candidate_index, candidate in enumerate(candidate_list): 416 | rcid = get_nested_value(candidate, [0]) 417 | if not rcid: 418 | continue # Skip candidate if it has no rcid 419 | 420 | # Text output and thoughts 421 | text = get_nested_value(candidate, [1, 0], "") 422 | if re.match( 423 | r"^http://googleusercontent\.com/card_content/\d+", text 424 | ): 425 | text = get_nested_value(candidate, [22, 0]) or text 426 | 427 | thoughts = get_nested_value(candidate, [37, 0, 0]) 428 | 429 | # Web images 430 | web_images = [] 431 | for web_img_data in get_nested_value(candidate, [12, 1], []): 432 | url = get_nested_value(web_img_data, [0, 0, 0]) 433 | if not url: 434 | continue 435 | 436 | web_images.append( 437 | WebImage( 438 | url=url, 439 | title=get_nested_value(web_img_data, [7, 0], ""), 440 | alt=get_nested_value(web_img_data, [0, 4], ""), 441 | proxy=self.proxy, 442 | ) 443 | ) 444 | 445 | # Generated images 446 | generated_images = [] 447 | if get_nested_value(candidate, [12, 7, 0]): 448 | img_body = None 449 | for img_part_index, part in enumerate(response_json): 450 | if img_part_index < body_index: 451 | continue 452 | try: 453 | img_part_body = get_nested_value(part, [2]) 454 | if not img_part_body: 455 | continue 456 | 457 | img_part_json = json.loads(img_part_body) 458 | if get_nested_value( 459 | img_part_json, [4, candidate_index, 12, 7, 0] 460 | ): 461 | img_body = img_part_json 462 | break 463 | except json.JSONDecodeError: 464 | continue 465 | 466 | if not img_body: 467 | raise ImageGenerationError( 468 | "Failed to parse generated images. Please update gemini_webapi to the latest version. " 469 | "If the error persists and is caused by the package, please report it on GitHub." 470 | ) 471 | 472 | img_candidate = get_nested_value( 473 | img_body, [4, candidate_index], [] 474 | ) 475 | 476 | if finished_text := get_nested_value( 477 | img_candidate, [1, 0] 478 | ): # Only overwrite if new text is returned after image generation 479 | text = re.sub( 480 | r"http://googleusercontent\.com/image_generation_content/\d+", 481 | "", 482 | finished_text, 483 | ).rstrip() 484 | 485 | for img_index, gen_img_data in enumerate( 486 | get_nested_value(img_candidate, [12, 7, 0], []) 487 | ): 488 | url = get_nested_value(gen_img_data, [0, 3, 3]) 489 | if not url: 490 | continue 491 | 492 | img_num = get_nested_value(gen_img_data, [3, 6]) 493 | title = ( 494 | f"[Generated Image {img_num}]" 495 | if img_num 496 | else "[Generated Image]" 497 | ) 498 | 499 | alt_list = get_nested_value(gen_img_data, [3, 5], []) 500 | alt = ( 501 | get_nested_value(alt_list, [img_index]) 502 | or get_nested_value(alt_list, [0]) 503 | or "" 504 | ) 505 | 506 | generated_images.append( 507 | GeneratedImage( 508 | url=url, 509 | title=title, 510 | alt=alt, 511 | proxy=self.proxy, 512 | cookies=self.cookies, 513 | ) 514 | ) 515 | 516 | output_candidates.append( 517 | Candidate( 518 | rcid=rcid, 519 | text=text, 520 | thoughts=thoughts, 521 | web_images=web_images, 522 | generated_images=generated_images, 523 | ) 524 | ) 525 | 526 | if not output_candidates: 527 | raise GeminiError( 528 | "Failed to generate contents. No output data found in response." 529 | ) 530 | 531 | output = ModelOutput( 532 | metadata=get_nested_value(body, [1], []), 533 | candidates=output_candidates, 534 | ) 535 | except (TypeError, IndexError) as e: 536 | logger.debug( 537 | f"{type(e).__name__}: {e}; Invalid response structure: {response.text}" 538 | ) 539 | raise APIError( 540 | "Failed to parse response body. Data structure is invalid." 541 | ) 542 | 543 | if isinstance(chat, ChatSession): 544 | chat.last_output = output 545 | 546 | return output 547 | 548 | def start_chat(self, **kwargs) -> "ChatSession": 549 | """ 550 | Returns a `ChatSession` object attached to this client. 551 | 552 | Parameters 553 | ---------- 554 | kwargs: `dict`, optional 555 | Additional arguments which will be passed to the chat session. 556 | Refer to `gemini_webapi.ChatSession` for more information. 557 | 558 | Returns 559 | ------- 560 | :class:`ChatSession` 561 | Empty chat session object for retrieving conversation history. 562 | """ 563 | 564 | return ChatSession(geminiclient=self, **kwargs) 565 | 566 | async def _batch_execute(self, payloads: list[RPCData], **kwargs) -> Response: 567 | """ 568 | Execute a batch of requests to Gemini API. 569 | 570 | Parameters 571 | ---------- 572 | payloads: `list[GRPC]` 573 | List of `gemini_webapi.types.GRPC` objects to be executed. 574 | kwargs: `dict`, optional 575 | Additional arguments which will be passed to the post request. 576 | Refer to `httpx.AsyncClient.request` for more information. 577 | 578 | Returns 579 | ------- 580 | :class:`httpx.Response` 581 | Response object containing the result of the batch execution. 582 | """ 583 | 584 | try: 585 | response = await self.client.post( 586 | Endpoint.BATCH_EXEC, 587 | data={ 588 | "at": self.access_token, 589 | "f.req": json.dumps( 590 | [[payload.serialize() for payload in payloads]] 591 | ).decode(), 592 | }, 593 | **kwargs, 594 | ) 595 | except ReadTimeout: 596 | raise TimeoutError( 597 | "Batch execute request timed out, please try again. If the problem persists, " 598 | "consider setting a higher `timeout` value when initializing GeminiClient." 599 | ) 600 | 601 | # ? Seems like batch execution will immediately invalidate the current access token, 602 | # ? causing the next request to fail with 401 Unauthorized. 603 | if response.status_code != 200: 604 | await self.close() 605 | raise APIError( 606 | f"Batch execution failed with status code {response.status_code}" 607 | ) 608 | 609 | return response 610 | 611 | 612 | class ChatSession: 613 | """ 614 | Chat data to retrieve conversation history. Only if all 3 ids are provided will the conversation history be retrieved. 615 | 616 | Parameters 617 | ---------- 618 | geminiclient: `GeminiClient` 619 | Async httpx client interface for gemini.google.com. 620 | metadata: `list[str]`, optional 621 | List of chat metadata `[cid, rid, rcid]`, can be shorter than 3 elements, like `[cid, rid]` or `[cid]` only. 622 | cid: `str`, optional 623 | Chat id, if provided together with metadata, will override the first value in it. 624 | rid: `str`, optional 625 | Reply id, if provided together with metadata, will override the second value in it. 626 | rcid: `str`, optional 627 | Reply candidate id, if provided together with metadata, will override the third value in it. 628 | model: `Model | str | dict`, optional 629 | Specify the model to use for generation. 630 | Pass either a `gemini_webapi.constants.Model` enum or a model name string to use predefined models. 631 | Pass a dictionary to use custom model header strings ("model_name" and "model_header" keys must be provided). 632 | gem: `Gem | str`, optional 633 | Specify a gem to use as system prompt for the chat session. 634 | Pass either a `gemini_webapi.types.Gem` object or a gem id string. 635 | """ 636 | 637 | __slots__ = [ 638 | "__metadata", 639 | "geminiclient", 640 | "last_output", 641 | "model", 642 | "gem", 643 | ] 644 | 645 | def __init__( 646 | self, 647 | geminiclient: GeminiClient, 648 | metadata: list[str | None] | None = None, 649 | cid: str | None = None, # chat id 650 | rid: str | None = None, # reply id 651 | rcid: str | None = None, # reply candidate id 652 | model: Model | str | dict = Model.UNSPECIFIED, 653 | gem: Gem | str | None = None, 654 | ): 655 | self.__metadata: list[str | None] = [None, None, None] 656 | self.geminiclient: GeminiClient = geminiclient 657 | self.last_output: ModelOutput | None = None 658 | self.model: Model | str | dict = model 659 | self.gem: Gem | str | None = gem 660 | 661 | if metadata: 662 | self.metadata = metadata 663 | if cid: 664 | self.cid = cid 665 | if rid: 666 | self.rid = rid 667 | if rcid: 668 | self.rcid = rcid 669 | 670 | def __str__(self): 671 | return f"ChatSession(cid='{self.cid}', rid='{self.rid}', rcid='{self.rcid}')" 672 | 673 | __repr__ = __str__ 674 | 675 | def __setattr__(self, name: str, value: Any) -> None: 676 | super().__setattr__(name, value) 677 | # update conversation history when last output is updated 678 | if name == "last_output" and isinstance(value, ModelOutput): 679 | self.metadata = value.metadata 680 | self.rcid = value.rcid 681 | 682 | async def send_message( 683 | self, 684 | prompt: str, 685 | files: list[str | Path] | None = None, 686 | **kwargs, 687 | ) -> ModelOutput: 688 | """ 689 | Generates contents with prompt. 690 | Use as a shortcut for `GeminiClient.generate_content(prompt, image, self)`. 691 | 692 | Parameters 693 | ---------- 694 | prompt: `str` 695 | Prompt provided by user. 696 | files: `list[str | Path]`, optional 697 | List of file paths to be attached. 698 | kwargs: `dict`, optional 699 | Additional arguments which will be passed to the post request. 700 | Refer to `httpx.AsyncClient.request` for more information. 701 | 702 | Returns 703 | ------- 704 | :class:`ModelOutput` 705 | Output data from gemini.google.com, use `ModelOutput.text` to get the default text reply, `ModelOutput.images` to get a list 706 | of images in the default reply, `ModelOutput.candidates` to get a list of all answer candidates in the output. 707 | 708 | Raises 709 | ------ 710 | `AssertionError` 711 | If prompt is empty. 712 | `gemini_webapi.TimeoutError` 713 | If request timed out. 714 | `gemini_webapi.GeminiError` 715 | If no reply candidate found in response. 716 | `gemini_webapi.APIError` 717 | - If request failed with status code other than 200. 718 | - If response structure is invalid and failed to parse. 719 | """ 720 | 721 | return await self.geminiclient.generate_content( 722 | prompt=prompt, 723 | files=files, 724 | model=self.model, 725 | gem=self.gem, 726 | chat=self, 727 | **kwargs, 728 | ) 729 | 730 | def choose_candidate(self, index: int) -> ModelOutput: 731 | """ 732 | Choose a candidate from the last `ModelOutput` to control the ongoing conversation flow. 733 | 734 | Parameters 735 | ---------- 736 | index: `int` 737 | Index of the candidate to choose, starting from 0. 738 | 739 | Returns 740 | ------- 741 | :class:`ModelOutput` 742 | Output data of the chosen candidate. 743 | 744 | Raises 745 | ------ 746 | `ValueError` 747 | If no previous output data found in this chat session, or if index exceeds the number of candidates in last model output. 748 | """ 749 | 750 | if not self.last_output: 751 | raise ValueError("No previous output data found in this chat session.") 752 | 753 | if index >= len(self.last_output.candidates): 754 | raise ValueError( 755 | f"Index {index} exceeds the number of candidates in last model output." 756 | ) 757 | 758 | self.last_output.chosen = index 759 | self.rcid = self.last_output.rcid 760 | return self.last_output 761 | 762 | @property 763 | def metadata(self): 764 | return self.__metadata 765 | 766 | @metadata.setter 767 | def metadata(self, value: list[str]): 768 | if len(value) > 3: 769 | raise ValueError("metadata cannot exceed 3 elements") 770 | self.__metadata[: len(value)] = value 771 | 772 | @property 773 | def cid(self): 774 | return self.__metadata[0] 775 | 776 | @cid.setter 777 | def cid(self, value: str): 778 | self.__metadata[0] = value 779 | 780 | @property 781 | def rid(self): 782 | return self.__metadata[1] 783 | 784 | @rid.setter 785 | def rid(self, value: str): 786 | self.__metadata[1] = value 787 | 788 | @property 789 | def rcid(self): 790 | return self.__metadata[2] 791 | 792 | @rcid.setter 793 | def rcid(self, value: str): 794 | self.__metadata[2] = value 795 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------