Package: gemini-webapi
Gemini-APIA reverse-engineered asynchronous python wrapper forGoogle Gemini(formerly Bard).FeaturesImageFx Support- Supports retrieving images generated by ImageFx, Google's latest AI image generator.Extension Support- Supports generating contents withGemini extensionson, like YouTube and Gmail.Classified Outputs- Auto categorizes texts, web images and AI generated images from the response.Official Flavor- Provides a simple and elegant interface inspired byGoogle Generative AI's official API.Asynchronous- Utilizesasyncioto run generating tasks and return outputs efficiently.Installationpipinstallgemini-webapiAuthenticationGo tohttps://gemini.google.comand login with your Google accountPress F12 for web inspector, go toNetworktab and refresh the pageClick any request and copy cookie values of__Secure-1PSIDand__Secure-1PSIDTSNote:__Secure-1PSIDTScould get expired frequently if the Google account is actively used elsewhere, especially when visitinghttps://gemini.google.comdirectly. It's recommended to use a separate Google account if you are builing a keep-alive service with this package.UsageInitializationImport required packages and initialize a client with your cookies obtained from the previous step.importasynciofromgeminiimportGeminiClient# Replace "COOKIE VALUE HERE" with your actual cookie valuesSecure_1PSID="COOKIE VALUE HERE"Secure_1PSIDTS="COOKIE VALUE HERE"asyncdefmain():client=GeminiClient(Secure_1PSID,Secure_1PSIDTS,proxy=None)awaitclient.init(timeout=30)asyncio.run(main())Generate contents from text inputsAsk a one-turn quick question by callingGeminiClient.generate_content.asyncdefmain():response=awaitclient.generate_content("Hello World!")print(response.text)asyncio.run(main())Note: simply useprint(response)to get the same output if you just want to see the response textConversations across multiple turnsIf you want to keep conversation continuous, please useGeminiClient.start_chatto create aChatSessionobject and send messages through it. The conversation history will be automatically handled and get updated after each turn.asyncdefmain():chat=client.start_chat()response1=awaitchat.send_message("Briefly introduce Europe")response2=awaitchat.send_message("What's the population there?")print(response1.text,response2.text,sep="\n\n----------------------------------\n\n")asyncio.run(main())Retrieve images in responseImages in the API's output are stored as a list ofImageobjects. You can access the image title, URL, and description by callingimage.title,image.urlandimage.altrespectively.asyncdefmain():response=awaitclient.generate_content("Send me some pictures of cats")forimageinresponse.images:print(image,"\n\n----------------------------------\n")asyncio.run(main())Generate image with ImageFxIn February 2022, Google introduced a new AI image generator called ImageFx and integrated it into Gemini. You can ask Gemini to generate images with ImageFx simply by natural language.Important: 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 fromofficial documentation(as of February 15th, 2024):Image generation in Gemini Apps is available in most countries, except in the European Economic Area (EEA), Switzerland, and the UK. It’s only available forEnglish prompts.This feature’s availability in any specific Gemini app is also limited to the supported languages and countries of that app.For now, this feature isn’t available to users under 18.asyncdefmain():response=awaitclient.generate_content("Generate some pictures of cats")forimageinresponse.images:print(image,"\n\n----------------------------------\n")asyncio.run(main())Note: 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 asWebImageandGeneratedImage, and will be automatically categorized in the output.Save images to local filesYou can save images returned from Gemini to local files under/tempby callingImage.save(). Optionally, you can specify the file path and file name by passingpathandfilenamearguments to the function. Works for bothWebImageandGeneratedImage.asyncdefmain():response=awaitclient.generate_content("Generate some pictures of cats")fori,imageinenumerate(response.images):awaitimage.save(path="temp/",filename=f"cat_{i}.png")asyncio.run(main())Generate contents with Gemini extensionsImportant: To access Gemini extensions in API, you must activate them on theGemini websitefirst. Same as image generation, Google also has limitations on the availability of Gemini extensions. Here's a summary copied fromofficial documentation(as of February 18th, 2024):To use extensions in Gemini Apps:Sign in with your personal Google Account that you manage on your own. Extensions, including the Google Workspace extension, are currently not available to Google Workspace accounts for school, business, or other organizations.Have Gemini Apps Activity on. Extensions are only available when Gemini Apps Activity is turned on.Important: For now, extensions are available inEnglish, Japanese, and Koreanonly.Note: for the last item, instead of region requirement, it actually only requires your Google account'spreferred languageto be set to one of the supported languages. You can change your language settingshere.Check and switch to other answer candidatesA response from Gemini usually contains multiple reply candidates with different generated contents. You can check all candidates and choose one to continue the conversation. By default, the first candidate will be chosen automatically.asyncdefmain():# Start a conversation and list all reply candidateschat=client.start_chat()response=awaitchat.send_message("What's the best Japanese dish? Recommend one only.")forcandidateinresponse.candidates:print(candidate,"\n\n----------------------------------\n")# Control the ongoing conversation flow by choosing candidate manuallynew_candidate=chat.choose_candidate(index=1)# Choose the second candidate herefollowup_response=awaitchat.send_message("Tell me more about it.")# Will generate contents based on the chosen candidateprint(new_candidate,followup_response,sep="\n\n----------------------------------\n\n")asyncio.run(main())ReferencesGoogle AI Studioacheong08/Bard