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
146 stars 9 forks source link

ValueError: Failed to parse SNlM0e nonce value from the response. Refresh the Gemini web page or access Gemini in a new incognito browser to resend cookies. If issue continues, export browser cookies, set manually. See auth section 3. #24

Open Usercodersystem opened 3 months ago

Usercodersystem commented 3 months ago

Hello Again I'm using GeminiClient = Gemini(auto_cookies=True)

But I got this error : if len(getattr(self, "cookies", {})) > 5: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: object of type 'NoneType' has no len()

versatile712 commented 3 months ago

same

dsdanielpark commented 3 months ago

This issue is not a package-level error; It is because Google has denied the request.

This could mean your account has been temporarily blocked due to frequent requests or your IP has been banned. There are some methods you can try, but ultimately, it means you failed to obtain the correct authentication from the Gemini server. Consider different workarounds related to your account, IP, and country. Temporary blocks may render it unavailable for several hours or days, and it is important to use it in a way that does not exceed rate limiting.

Possible actions include changing your IP and account. We cannot help as this is not a package-level error.

Please actively report other issues and improve our package code.

We always welcome contributors.

versatile712 commented 3 months ago

thanks, but a new problem occured.

ValueError                                Traceback (most recent call last)
Cell In[6], [line 2](vscode-notebook-cell:?execution_count=6&line=2)
      [1](vscode-notebook-cell:?execution_count=6&line=1) from gemini import Gemini
----> [2](vscode-notebook-cell:?execution_count=6&line=2) GeminiClient = Gemini(auto_cookies=True)
      [3](vscode-notebook-cell:?execution_count=6&line=3) # GeminiClient = Gemini(auto_cookies=True, target_cookies = ["__Secure-1PSID", "__Secure-1PSIDTS"]) # Can select cookies.
      [4](vscode-notebook-cell:?execution_count=6&line=4) response = GeminiClient.generate_content("Hello, Gemini. What's the weather like in Seoul today?")

File [c:\Users\user\anaconda3\envs\geminiapi\lib\site-packages\gemini\core.py:71](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:71), in Gemini.__init__(self, session, cookies, cookie_fp, auto_cookies, target_cookies, timeout, proxies)
     [69](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:69) self.proxies = proxies or {}
     [70](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:70) self.timeout = timeout
---> [71](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:71) self.session = session or self._initialize_session()
     [72](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:72) self.base_url: str = URLs.BASE_URL.value
     [73](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:73) self.parser = ResponseParser(cookies=self.cookies)

File [c:\Users\user\anaconda3\envs\geminiapi\lib\site-packages\gemini\core.py:114](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:114), in Gemini._initialize_session(self)
    [111](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:111) elif self.auto_cookies == True:
    [112](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:112)     self._set_cookies_automatically()
--> [114](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:114) self._set_sid_and_nonce()
    [116](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:116) return session

File [c:\Users\user\anaconda3\envs\geminiapi\lib\site-packages\gemini\core.py:162](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:162), in Gemini._set_sid_and_nonce(self)
    [160](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:160)     raise ConnectionError(f"Request failed: {e}")
    [161](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:161) except ValueError as e:
--> [162](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:162)     raise e  # Re-raise the exception after it's caught
...
    [160](file:///C:/Users/user/anaconda3/envs/geminiapi/lib/site-packages/gemini/core.py:160)     raise ConnectionError(f"Request failed: {e}")

ValueError: Failed to parse SNlM0e nonce value from the response.
Refresh the Gemini web page or access Gemini in a new incognito browser to resend cookies. 
If issue continues, export browser cookies, set manually. See auth section 3.
dsdanielpark commented 3 months ago

Firstly, try this codes as sequencially:

from gemini import Gemini

GeminiClient = Gemini(auto_cookies=True)

GeminiClient = Gemini(auto_cookies=True, target_cookies = ["__Secure-1PSIDCC"]) 

GeminiClient = Gemini(auto_cookies=True, target_cookies = ["__Secure-1PSID", "__Secure-1PSIDTS"]) 

GeminiClient = Gemini(auto_cookies=True, target_cookies = ["__Secure-1PSIDCC", " __Secure-1PSID", "__Secure-1PSIDTS", "NID"]) 

response = GeminiClient.generate_content("Hello, Gemini. What's the weather like in Seoul today?")
print(response.payload)

If you're still receiving a blank response or it's not working, try passing the entire cookie as a last resort. Reset Chrome by removing all login information and cookies, then export and share the entire cookie using one account on Chrome. Use a browser extension to export and pass the entire cookie.

versatile712 commented 3 months ago

Thanks for your reply. I tried all the codes you provided, and even when I add cookies manaully, the error still exsits. I think it may have nothing to do with automated cookie collection.

dsdanielpark commented 3 months ago

versatile712

Realted this issue #14.

I have a cookie set that works on one laptop for nearly a month, but not on another, only returning empty responses. It might need more handling related to RotateCookie and exceptions, but I'm too busy with important schedules to spend much time on it.

Please share any solutions you find. I couldn't capture the nonce value with auto cookie but had no issues otherwise.

It might be necessary to reset all data through logins and logouts in different environments and properly define it using the ExportCookie extension.

Once I'm free, I plan to experiment with various accounts to find a solution.

OlegRuban-ai commented 3 months ago

@dsdanielpark

Hello! Is it possible to use the automatic collection option on a remote server without GUI?

Usercodersystem commented 3 months ago

Very thanks

Usercodersystem commented 3 months ago

Problem Fixed but new Problem is shown 😑🤣

ValueError: Failed to parse SNlM0e nonce value from the response. Refresh the Gemini web page or access Gemini in a new incognito browser to resend cookies. If issue continues, export browser cookies, set manually. See auth section 3.

dsdanielpark commented 3 months ago

Usercodersystem

This is what I plan to fix. I will check RotateCookie endpoint!

I have importanct interview tomorrow! Thus, I will fix that issue until next weekend. Try to check this code https://github.com/dsdanielpark/Gemini-API?tab=readme-ov-file Reqid may not be useful.

Usercodersystem commented 3 months ago

OK very thanks for answering me:)

rahulp7801 commented 3 months ago

Is there an update on this yet? I am also having the same issue

ilmal commented 3 months ago

I've got the same problem

dsdanielpark commented 3 months ago

rahulp7801, ilmal

Have you tried using all the cookies after resetting all account information in the browser (if necessary, log out and erase all information)?

ilmal commented 3 months ago

Just tried it (removed all cookies and logged back in again), the same err:

ValueError: Failed to parse SNlM0e nonce value from the response. Refresh the Gemini web page or access Gemini in a new incognito browser to resend cookies. If issue continues, export browser cookies, set manually. See auth section 3.

This is my code:

cookies = {} # FROM COOKIE EXTRENSION
GeminiClient = Gemini(cookies=cookies)

response = GeminiClient.generate_content("Hello, Gemini. What's the weather like in Seoul today?")
print(response.payload)
Usercodersystem commented 3 months ago

@ilmal try another browser like Firefox or same To get cookie

ilmal commented 3 months ago

Just tried with firefox, same err when I selected cookies manually, automatically.

I use this version if that is relevant:

$ pip3 list | grep gemini

python-gemini-api            2.4.1
galihmrd commented 3 months ago

Same issue, Now i back to older version, it works smoothly

ilmal commented 3 months ago

Thank you, pushed it back to v2.2.1 and now I get another err:

raise ValueError("All parsing strategies failed.")
ValueError: All parsing strategies failed.

I cant find an prev issue with this err, anyone know what causes this? Also, thanks for all the help! :)

dsdanielpark commented 3 months ago

In fact, there's no significant change in the logic used across versions. However, I've also observed that the same cookies work on one laptop but not on another.

Thus, it might be beneficial to refresh and retry cookies in various environments.

To reiterate, once the entire cookie set is established, it tends to remain stable on a single PC for a long time.

galihmrd Could you tell me what version you used?

ilmal Hello,

There has been no change in the auth token collection algorithm between versions 2.4.2 and 2.4.1, though there might be changes in the parsing method.

You can check as follows:

There are four parsing methods, and version 2.4.2 tries various parsing approaches. Therefore, ensure that the payload received before parsing is correct.

from gemini import Gemini

cookies = {} # Cookies may vary by account or region. Consider sending the entire cookie file.
GeminiClient = Gemini(cookies=cookies) # You can use various args

response_text, response_status = GeminiClient.send_request("Hello, Gemini. What's the weather like in Seoul today?")
print(response_text)
galihmrd commented 3 months ago

Now I'm using version 2.2.1

dsdanielpark commented 3 months ago

Now I'm using version 2.2.1

Could you kindly try to use version 2.4.1? On a same PC using same Cookies, using different enviroment (e.g., via conda env conda create -n temp,conda activate temp, and pip install python-gemini-api==2.4.1)

Thank you!

ilmal commented 3 months ago

I tried using another laptop with another browser, but still got the same problem. Not sure what I can do to force a cookie refresh.

dsdanielpark commented 3 months ago

ilmal

  1. If you're using the Chrome browser, first log out of all accounts, including synced accounts, to prevent the browser from remembering any accounts.
  2. Alternatively, download a completely new browser and try using an extension to export all cookies.
  3. Lastly, create a new Google account, set the location to Ukraine or another country, then log in using a browser with no account information and export all cookies.

I recommend trying the third method with a new browser and suggest attempting it locally rather than on servers like Colab.

dsdanielpark commented 3 months ago

Hi, guys! ilmal, galihmrd, Usercodersystem, rahulp7801, OlegRuban-ai, versatile712

Sorry, It's my mistake. I was busy to review my code and I found some mistake in recent version.

Gemini API 2.4.2

I may fixed this issue. Try to use 2.4.2

pip install python-gemini-api==2.4.2

or

pip install -q -U python-gemini-api

I will not close this issue, becuase it may occured by different reasons.

ilmal commented 3 months ago

I tried to run with v2.4.2 but get the same err:

ValueError: Failed to parse SNlM0e nonce value from the response.
Refresh the Gemini web page or access Gemini in a new incognito browser to resend cookies. 
If issue continues, export browser cookies, set manually. See auth section 3.

The problem seems to be with your cookie sorter. I removed this code from the client.py file:

        # Delete non-target cookies
        if self.target_cookies == None:
            self.cookies = {
                key: value
                for key, value in self.cookies.items()
                if key in TARGET_COOKIES
            }

And with that I got past the err. So I think you remove more cookies that you should here.

But I'm not quite all the way fixed yet. By running your code:

response_text, response_status = GeminiClient.send_request("Hello, Gemini. What's the weather like in Seoul today?")
print(response_text)

I get:

)]}'

38
[["wrb.fr",null,null,null,null,[7]]]
54
[["di",44],["af.httprm",44,"6932734665177824398",1]]
25
[["e",4,null,null,129]]

Which I still find a bit cryptic. But at least the cookie problem seems to be resolved by just passing all cookies from the auto collect! :)

dsdanielpark commented 3 months ago

As stated in the readme, it's essential to experiment in various environments to determine where target_cookies function effectively. However, in my case, providing the entire set of cookies when experimenting with accounts in Korea, Ukraine, and the USA via VPN proved to be effective. Therefore, I believe that providing the complete set of cookies works well.

Most of the errors seem to occur due to the inability to reset cookies remaining in the browser or the presence of other account information in Chrome, although I haven't been able to confirm this due to time constraints. Nonetheless, I strongly believe that resetting the browser and manually updating the cookie values are crucial. (Refer to the last advice about using a different browser if unsure.)


Firstly, regarding the issue with cookies, I have update "all" option in target_cookies arguments.

If you wish to experiment with the current cookie values, simply provide the desired cookie key values as arguments in the form of a 1D list to target_cookies.

target_cookies=["__Secure-1PSID", "__Secure-1PSIDTS"]
GeminiClient = Gemini(auto_cookies=True, target_cookies=target_cookies)

I have update "all" option of target_cookies variable in 3e41cedd23ec0cb874289fd7d75503d95001fc52 This will be released in 2.4.4, Thus you can install github version by using this command. (pip install git+https://github.com/dsdanielpark/Gemini-API.git)

GeminiClient = Gemini(auto_cookies=True, target_cookies="all")

Lastly, as you suggested, manually providing cookies is indeed crucial!

However, it's advisable to completely log out of the browser to forcefully reset the cookie values. If handling this aspect with Chrome poses difficulty, consider using alternative browsers like Firefox or Brave and try using the "Export Cookie" extension!

I strongly recommend exporting cookies through a browser other than Chrome.

After reinstalling the cookie values manually, please give it a try. Once you succeed once, please remain hopeful!

Sincere gratitude for your consistent feedback! Wishing you success.

skills-up commented 2 months ago

Tried everything on this thread, still getting the issue:

File "/miniconda3/lib/python3.12/site-packages/gemini/client.py", line 160, in _set_sid_and_nonce
    raise ValueError(
ValueError: Failed to parse SNlM0e nonce value from the response.
Refresh the Gemini web page or access Gemini in a new incognito browser to resend cookies. 
If issue continues, export browser cookies, set manually. See auth section 3.
dsdanielpark commented 2 months ago

skills-up

Authentication issues are likely related to account or IP problems. Have you considered using a paid VPN or services like Crawbase, and have you tried passing all cookies?

skills-up commented 2 months ago

I tried incognito mode, and even tor browser (despite its sluggishness). I've also passed all the cookies manually. Still the same issue persists.

dsdanielpark commented 2 months ago

Have you followed all the instructions in the authentication section?

  1. If you have used it successfully before but encountered authentication issues:

    • There could be a temporary block from Google’s peer side, which may last a few hours to several days.
  2. If you have never been able to use it properly:

    • You might not receive proper requests due to errors like 429 or CAPTCHAs.
    • While TOR or other browsers may not have cached cookies, making cookie collection straightforward, the code-level requests are likely still coming from your server or personal laptop’s IP. The Tor browser, despite having a browser-side VPN, does not mask your IP for REST formatted requests. Consider using a proxy server to bypass IP restrictions.

Due to the multitude of factor involved, I’m unable to provide package-level debugging. It’s possible that regional, account, or IP-based factors are affecting functionality.