dsdanielpark / Gemini-API

The unofficial python package that returns response of Google Gemini through cookie values.
https://pypi.org/project/python-gemini-api/
MIT License
160 stars 14 forks source link

Unable to reuse sessions. #20

Closed aniruddhkrish closed 6 months ago

aniruddhkrish commented 6 months ago

Could you please provide me the code for using Gemini API, in a reusable session? Please do the needful and its my humble request.

dsdanielpark commented 6 months ago

I updated buy usally you can reuse session by declaring Gemini class once.

If you want to fix context, consider this codes.

Thank you!

08. Fix context setting rcid

You can specify a particular response by setting its response candidate id(rcid).

# Generate content for the prompt "Give me some information about the USA."
response1 = GeminiClient.generate_content("Give me some information about the USA.")
# After reviewing the responses, choose the one you prefer and copy its RCID.
GeminiClient.rcid = "rc_xxxx"

# Now, generate content for the next prompt "How long does it take from LA to New York?"
response2 = GeminiClient.generate_content("How long does it take from LA to New York?")

09. Changing the Selected Response from 0 to n

In Gemini, generate_content returns the first response. This may vary depending on length or sorting. Therefore, you can specify the index of the chosen response from 0 to n as follows. However, if there is only one response, revert it back to 0.

from gemini import GeminiModelOutput
GeminiModelOutput.chosen = 1 # default is 0
response1 = GeminiClient.generate_content("Give me some information about the USA.")

Reusable session object

Gemini class suffices for most cases, but use session objects for special cases.

from gemini import Gemini, HEADERS
import requests
cookies = {} 

session = requests.Session()
session.headers = HEADERS

GeminiClient = Gemini(cookies=cookies) # You can use various args
response = GeminiClient.generate_content("Hello, Gemini. What's the weather like in Seoul today?")