Package: python-gemini-api
Development Status :: 1 - PlanningNot ready yet. Development and QA for the service underway from March 1st, 2024.Google - Gemini APIA Python wrapper,python-gemini-api, interacts withGoogle Geminivia reverse engineering.What isGemini?Gemini is a family of generative AI models developed by Google DeepMind that is designed for multimodal use cases. The Gemini API gives you access to the Gemini Pro and Gemini Pro Vision models. In February 2024, Google'sGeminiservice was changed toGemini.Paper,Official WebInstallationpip install python-gemini-apipip install git+https://github.com/dsdanielpark/Gemini-API.gitAuthenticationWarningDO NOTexpose your cookies.Cookie requirements may vary based on country/regions and the status of your Google account.Visithttps://gemini.google.com/F12 for consoleSession: Application → Cookies → Copy the value of__Secure-1PSIDTS,__Secure-1PSIDCC,__Secure-1PSID,NIDcookie orSIDCCcookie.
Depending on the region and Google account status,multiple cookies may be required.UsageAfter changed Bard to Gemini, multiple cookies,often updated, are needed based on region or Google account. Thus, automatic cookie renewal logic is crucial.InitializationYou must appropriately set thecookies_dictparameter toGeminiclass.Needed cookie values may vary by country/region/account.Async clientfromgeminiimportGeminiClientcookies={"__Secure-1PSID":"value","__Secure-1PSIDTS":"value","__Secure-1PSIDCC":"value","NID":"value",}client=GeminiClient(cookies=cookies)# client = GeminiClient(auto_cookies=True) # Or use auto_cookies paprameterawaitclient.async_init()Sync sessionfromgeminiimportGeminicookies={"SIDCC":"value"}client=Gemini(cookies=cookies)# client = Gemini(auto_cookies=True) # Or use auto_cookies paprameterCan update cookies automatically usingbroser_cookie3. Cookie values can be changed frequently, thus it is recommended to automatically update.Before proceeding, ensure that the GeminiClient object is defined without any errors.Text generationprompt="Hello, Gemini. What's the weather like in Seoul today?"response=GeminiClient.generate_content(prompt)print(response)Image generationprompt="Hello, Gemini. Give me a beautiful photo of Seoul's scenery."response=GeminiClient.generate_content(prompt)print("\n".join(response.images))# Print imagesfori,imageinenumerate(response.images):# Save imagesimage.save(path="folder_path/",filename=f"seoul_{i}.png")Generate content with imageIt may not work as it is only available for certain accounts, regions, and other restrictions.As an experimental feature, it is possible to ask questions with an image. However, this functionality is only available for accounts with image upload capability in Gemini's web UI.prompt="What is in the image?"image=open("folder_path/image.jpg","rb").read()# (jpeg, png, webp) are supported.response=GeminiClient.generate_content(prompt,image)Text To Speech(TTS)from GeminiBusiness users and high traffic volume may be subject to account restrictions according to Google's policies. Please use theOfficial Google Cloud APIfor any other purpose.text="Hello, I'm developer in seoul"# Gemini will speak this sentenceresponse=GeminiClient.generate_content(prompt)audio=GeminiClient.speech(text)withopen("speech.ogg","wb")asf:f.write(bytes(audio["audio"]))FurtherBehind a proxyIf you are working behind a proxy, use the following.proxies={"http":"http://proxy.example.com:8080","https":"https://proxy.example.com:8080"}GeminiClient=Gemini(cookies=cookies,proxies=proxies,timeout=30)GeminiClient.generate_content("Hello, Gemini. Give me a beautiful photo of Seoul's scenery.")Use rotating proxiesIf you want toavoid blocked requestsand bans, then useSmart Proxy by Crawlbase. It forwards your connection requests to arandomly rotating IP addressin a pool of proxies before reaching the target website. The combination of AI and ML make it more effective to avoid CAPTCHAs and blocks.# Get your proxy url at crawlbase https://crawlbase.com/docs/smart-proxy/get/proxy_url="http://xxxxx:@smartproxy.crawlbase.com:8012"proxies={"http":proxy_url,"https":proxy_url}GeminiClient=Gemini(cookies=cookies,proxies=proxies,timeout=30)GeminiClient.generate_content("Hello, Gemini. Give me a beautiful photo of Seoul's scenery.")Reusable session objectYou can continue the conversation using a reusable session. However, this feature is limited, and it is difficult for a package-level feature to perfectly maintain context. You can try to maintain the consistency of conversations same way as other LLM services, such as passing some sort of summary of past conversations to the DB.fromgeminiimportGemini,SESSION_HEADERSimportrequestscookies={"__Secure-1PSID":"value","__Secure-1PSIDTS":"value","__Secure-1PSIDCC":"value","NID":"value",}session=requests.Session()session.headers=SESSION_HEADERSsession.cookies.update(cookies)GeminiClient=Gemini(session=session,timeout=30)response=GeminiClient.generate_content("Hello, Gemini. What's the weather like in Seoul today?")# Continued conversation without set new sessionresponse=GeminiClient.generate_content("What was my last prompt?")More featuresChat GeminiGet image linksMulti-language GeminiExport ConversationExport Code to Repl.itExecuting Python code received as a response from GeminiMax_token, Max_sentencesTranslation to another programming languageHow to use open-sourceGemmaGemma models are Google's lightweight, advanced text-to-text, decoder-only language models, derived from Gemini research. Available in English, they offer open weights and variants, ideal for tasks like question answering and summarization. Their small size enables deployment in resource-limited settings, broadening access to cutting-edge AI. For more infomation, visitGemma-7bmodel card.fromtransformersimportAutoTokenizer,AutoModelForCausalLMtokenizer=AutoTokenizer.from_pretrained("google/gemma-7b")model=AutoModelForCausalLM.from_pretrained("google/gemma-7b")input_text="Write me a poem about Machine Learning."input_ids=tokenizer(input_text,return_tensors="pt")outputs=model.generate(**input_ids)print(tokenizer.decode(outputs[0]))UseCrawlbaseAPI for efficient data scraping to train AI models, boasting a 98% success rate and 99.9% uptime. It's quick to start, GDPR/CCPA compliant, supports massive data extraction, and is trusted by 70k+ developers.FAQYou can find most help on theFAQandIssuepages. Alternatively, utilize the official Gemini API atGoogle AI Studio.IssuesSincerely grateful for any reports on new features or bugs. Your valuable feedback on the code is highly appreciated. Frequent errors may occur due to changes in Google's service API interface. BothIssue reportsandPull requestscontributing to improvements are always welcome. We strive to maintain an active and courteous open community.ContributorsWe would like to express my sincere gratitude to all the contributors.ContactsCore Maintainer:Minwoo(Daniel) Park,@dsdanielparkE-mail:parkminwoo1991@gmail.comLicenseMITlicense, 2024, Minwoo(Daniel) Park. We hereby strongly disclaim any explicit or implicit legal liability related to our works. Users are required to use this package responsibly and at their own risk.References[1] Githubacheong08/Bard[2] GithubGoogleCloudPlatform/generative-ai[3] GithubHanaokaYuzu/Gemini-API[4]Google AI StudioWarningUsers bear all legal responsibilities when using the GeminiAPI package, which offers easy access to Google Gemini for developers. This unofficial Python package isn't affiliated with Google and may lead to Google account restrictions if used excessively or commercially due to its reliance on Google account cookies. Frequent changes in Google's interface, Google's API policies, and your country/region, as well as the status of your Google account, may affect functionality. Utilize the issue page and discussion page.Copyright (c) 2024 Minwoo(Daniel) Park, South Korea