dsdanielpark / gemini-api Goto Github PK
View Code? Open in Web Editor NEWThe unofficial python package that returns response of Google Gemini through cookie values.
Home Page: https://pypi.org/project/python-gemini-api/
License: MIT License
The unofficial python package that returns response of Google Gemini through cookie values.
Home Page: https://pypi.org/project/python-gemini-api/
License: MIT License
Could you please provide me the code for using Gemini API, in a reusable session? Please do the needful and its my humble request.
Tried running the example code
from gemini import OpenRouter
api_key = "<your_api_key>"
gemma_client = OpenRouter(api_key=api_key, model="google/gemma-7b-it:free")
prompt = "Do you know UCA academy in Korea?"
response = gemma_client.create_chat_completion(prompt)
print(response)
and i got the error
Traceback (most recent call last):
File "C:\Users\alima\PycharmProjects\Vent_Linkedin_bot\Test.py", line 2, in <module>
from gemini import OpenRouter
File "C:\Users\alima\PycharmProjects\Vent_Linkedin_bot\venv\lib\site-packages\gemini\__init__.py", line 5, in <module>
from .src.modules.openrouter.client import OpenRouter
File "C:\Users\alima\PycharmProjects\Vent_Linkedin_bot\venv\lib\site-packages\gemini\src\modules\openrouter\__init__.py", line 1, in <module>
from .client import OpenRouter
File "C:\Users\alima\PycharmProjects\Vent_Linkedin_bot\venv\lib\site-packages\gemini\src\modules\openrouter\client.py", line 2, in <module>
from const import FreeModel
ModuleNotFoundError: No module named 'const'
Might want to either have it auto install or put it in the git somewhere
from .utils import (
ImportError: cannot import name 'extract_cookies_from_brwoser' from 'gemini.utils'
Please compile the major issues here until then. We are aware of most errors during the development process, and we are continuously working to make the error messages clearer.
Currently, we are focusing on checking the logic for receiving a normal response through reverse engineering and for automatically updating the cookie values in real-time.
Additionally, you can contribute to the initial package development at any time through a pull request. Any type of contribution is appreciated, but we ask for a significant amount of development for your first pull request.
Thank you.
Failed to generate content due to an error: All parsing strategies failed. Try to use Gemini.send_request(prompt)
to get original payload..
Return reponse without parse. If the issue persists, submit it at https://github.com/dsdanielpark/Gemini-API/issues
)]}'
Hello Bard API contributors,
Are you keeping well?
We are in the process of redeveloping a Python package that works with the updated Gemini, with the kind assistance of Antonio Cheong.
I hope this message finds you well. I wanted to inform you that with the transition from Bard to Gemini, we have updated the package repository accordingly.
There have been some slight changes in the parser section. However, I apologize for proceeding with the transition without your permission, driven by the desire to clean up the previous codebase.
Once the existing package stabilizes to some extent, we plan to override it from Bard API. For now, we will gradually port the legacy codes from the Gemini-API package repository.
If any of you, Bard API contributors, could submit even an empty commit to the Gemini-API, we will promptly merge it. Additionally, your assistance in various tasks such as porting legacy codes, documentation, etc., would be greatly appreciated.
I wish you all a happy and prosperous year in 2024, and please feel free to reach out if there's anything I can assist you with!
Thank you and gratitude for your contributions.
Best regards,
Daniel
CBoYXD, veonua, thewh1teagle, jjkoh95, yihong0618, nishantchauhan949, MeemeeLab, #9kota113, sachnun, amit9021, zeelsheladiya, ayansengupta17, thecodekitchen, SalimLouDev, Qewertyy, senseibence, mirusu400, szv99, sudoAlireza
Describe the bug
The response text is returned in a URL format that cannot be seen.
Version
OS: Windows 11
Python: 3.12.2
Gemini API: 1.0.4
Using proxy: No
Region: Poland
Code
from gemini import Gemini
cookies = {
"__Secure-1PSID" : "fullfilled",
"__Secure-1PSIDTS" : "fullfilled",
"__Secure-1PSIDCC" : "fullfilled", # I use this because in BardCookies it works
"NID" : "fullfilled",
}
GeminiClient = Gemini(cookies=cookies)
prompt = "Hello, Gemini. What's the weather like in Seoul today?"
response = GeminiClient.generate_content(prompt)
print(response)
Error
{'metadata': ['c_cd648c1c943cb00f', 'r_f093111e78855c35'], 'candidates': {'rcid': 'rc_97ec8a9d7ddbed62', 'text': 'http://googleusercontent.com/card_content/0', 'web_images': [], 'generated_images': []}}
My gemini api version = 2.1.0
Traceback (most recent call last):
File "C:\Users\Gumus\Desktop\gemini_api\main.py", line 7, in
response = GeminiClient.generate_content("Bu resmi bana açıklarmısın?", image=image_path)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gumus\AppData\Local\Programs\Python\Python312\Lib\site-packages\gemini\core.py", line 263, in generate_content
return self._create_model_output(parsed_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gumus\AppData\Local\Programs\Python\Python312\Lib\site-packages\gemini\core.py", line 275, in _create_model_output
candidates = self.collect_candidates(parsed_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gumus\AppData\Local\Programs\Python\Python312\Lib\site-packages\gemini\core.py", line 308, in collect_candidates
collected.append(GeminiCandidate(**current))
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Gumus\AppData\Local\Programs\Python\Python312\Lib\site-packages\pydantic\main.py", line 171, in init
self.pydantic_validator.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 1 validation error for GeminiCandidate
code
Input should be a valid list [type=list_type, input_value='Gönderilen resimde "Saf...ihtimalini artırıyor.', input_type=str]
For further information visit https://errors.pydantic.dev/2.6/v/list_type
ImportError: cannot import name 'Gemini' from 'gemini' (/home/runner/Bard-ai/.pythonlibs/lib/python3.10/site-packages/gemini/init.py)
Code Used:
from gemini import Gemini, GeminiImage
prompt = "Create illustrations of Seoul, South Korea."
response = GeminiClient.generate_content(prompt)
generated_images = response.generated_images # Check generated images [Dict]
GeminiImage.save_sync(generated_images, save_path="cached_folder")
Error:
Failed to download https://lh3.googleusercontent.com/bard/ADjfeTdRTWhsRmVFNH5LQJ7DRSghoivB2a50_FohrJQJtWe6CS4IMBWjjYcLFxgEUn6LtcC8dbM9wPOtxuJO92Ez_RhqcfZnH9k5EFwjL5YvCLy2PPC9jKy9PCDiONVJvAa47YD6K_XPWSjpK84_GoI1gHC6T4GUNj-FP3ezLqJjrofV1gUBFn7SBDLykYKrU7_o_xK0iaCs3Kb_UkpSpUqc5MRqaMQoMCf4EQm8gjVSFnfGGI43fcGs7CPb6_5ey4os203Hv8JA-SoyF1bYzF718H6Kq0D01dAq4KiC86aB1HzDcEpwWElOHBAxcQ9qAUHWWRpleUfq3ZZUOd4MS1o: Invalid type for url. Expected str or httpx.URL, got <class 'pydantic_core._pydantic_core.Url'>: Url('https://lh3.googleusercontent.com/bard/ADjfeTdRTWhsRmVFNH5LQJ7DRSghoivB2a50_FohrJQJtWe6CS4IMBWjjYcLFxgEUn6LtcC8dbM9wPOtxuJO92Ez_RhqcfZnH9k5EFwjL5YvCLy2PPC9jKy9PCDiONVJvAa47YD6K_XPWSjpK84_GoI1gHC6T4GUNj-FP3ezLqJjrofV1gUBFn7SBDLykYKrU7_o_xK0iaCs3Kb_UkpSpUqc5MRqaMQoMCf4EQm8gjVSFnfGGI43fcGs7CPb6_5ey4os203Hv8JA-SoyF1bYzF718H6Kq0D01dAq4KiC86aB1HzDcEpwWElOHBAxcQ9qAUHWWRpleUfq3ZZUOd4MS1o')
Failed to download https://lh3.googleusercontent.com/bard/ADjfeTcTUw6txdmEd2o1EWED4rK5thrOeZO5xygpxYAy4fSkpd7qUuSBrtRafc5m9bYdbgoivXVKQEFWA7sXw3JHMnMi4BhM6q_dpEjiCIHxRloVLWJ7NRPTvmz_uf4gUrga3u0TSpo0OkIBlIdakvlj4WRy_dftihKOMwdarrrkrCM08rTPjnE5ASuvZC9RtD9xgaxpIGMfBAH1iXJRs6EHd9mQwiN03tlyHz_p0gXkV-H6y670lXCngR9h6ZCire0jJYsSLiU7HL0xu1_PLBDNylb7IDDzNWT1bN_ZVdx15jAb03jG5Plp38uJ3L8bEkAxDJVjV5E601d9eO-jD5Q: Invalid type for url. Expected str or httpx.URL, got <class 'pydantic_core._pydantic_core.Url'>: Url('https://lh3.googleusercontent.com/bard/ADjfeTcTUw6txdmEd2o1EWED4rK5thrOeZO5xygpxYAy4fSkpd7qUuSBrtRafc5m9bYdbgoivXVKQEFWA7sXw3JHMnMi4BhM6q_dpEjiCIHxRloVLWJ7NRPTvmz_uf4gUrga3u0TSpo0OkIBlIdakvlj4WRy_dftihKOMwdarrrkrCM08rTPjnE5ASuvZC9RtD9xgaxpIGMfBAH1iXJRs6EHd9mQwiN03tlyHz_p0gXkV-H6y670lXCngR9h6ZCire0jJYsSLiU7HL0xu1_PLBDNylb7IDDzNWT1bN_ZVdx15jAb03jG5Plp38uJ3L8bEkAxDJVjV5E601d9eO-jD5Q')
Failed to download https://lh3.googleusercontent.com/bard/ADjfeTc1HGdWthxSjOuYeEUr5l3KPLTCuZyPrQEs9O0tD0eM-wZj_XDtjVX8i9-BqrW6EScAKpw29MMnaunZGANeLH1K16C2avYWUXDqY5zBQ3oqHVvWffUcN6YTZij3smFZ-58KzvC51E2t20Jayd9rYWcn6ZyZKV3cKEEQ2Lx1fV8zSyBIT5MMNdII6QofiV2hlvNKmC6QF5n8cC0ZejEvhDOLctw_IIosJWX3jh-bAPnNf8GmqEVoFBd6253ewoCUOlxDcaey9Iyn_q7CiXrj_f0rOx3kYVnPQGexZHnE3718Wa7Aum0l8EEcjZpsqcniOIEyFYIu2dw4zmsN2Do: Invalid type for url. Expected str or httpx.URL, got <class 'pydantic_core._pydantic_core.Url'>: Url('https://lh3.googleusercontent.com/bard/ADjfeTc1HGdWthxSjOuYeEUr5l3KPLTCuZyPrQEs9O0tD0eM-wZj_XDtjVX8i9-BqrW6EScAKpw29MMnaunZGANeLH1K16C2avYWUXDqY5zBQ3oqHVvWffUcN6YTZij3smFZ-58KzvC51E2t20Jayd9rYWcn6ZyZKV3cKEEQ2Lx1fV8zSyBIT5MMNdII6QofiV2hlvNKmC6QF5n8cC0ZejEvhDOLctw_IIosJWX3jh-bAPnNf8GmqEVoFBd6253ewoCUOlxDcaey9Iyn_q7CiXrj_f0rOx3kYVnPQGexZHnE3718Wa7Aum0l8EEcjZpsqcniOIEyFYIu2dw4zmsN2Do')
Traceback (most recent call last):
File "/home/container/app.py", line 37, in <module>
GeminiImage.save_sync(generated_images, save_path="cached_folder")
File "/home/container/.local/lib/python3.11/site-packages/gemini/src/model/image.py", line 116, in save_sync
GeminiImage.validate_images(image_data)
File "/home/container/.local/lib/python3.11/site-packages/gemini/src/model/image.py", line 20, in validate_images
raise ValueError("Input is empty. Please provide images to proceed.")
ValueError: Input is empty. Please provide images to proceed.
💚💜 Thank you for interest. ❤️💛
Please make sure to check for more efficient package management.
To Reproduce
Describe the bug
not working gemini, writes ↓
Version
OS: Win11
Python: 3.11.7
Gemini API: usa
Using proxy: no
Legion:
Code
cookies = {
"key": google_api_key # google_api_key : str
}
GeminiClient = Gemini(cookies=cookies)
Error
'NoneType' object has no attribute 'group'
File "D:\MH\gemini.py", line 18, in <module>
GeminiClient = Gemini(cookies=cookies)
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'group'
Code :
client = Gemini(cookie_fp="cookies.txt")
response = client.generate_content("Hello, Gemini. What's the weather like in Seoul today?")
response.payload
Error:
AttributeError Traceback (most recent call last)
[<ipython-input-6-25dd85f77876>](https://localhost:8080/#) in <cell line: 3>()
1 from gemini import Gemini
2
----> 3 client = Gemini(cookie_fp="cookies.txt")
4
5 response = client.generate_content("Hello, Gemini. What's the weather like in Seoul today?")
2 frames
[/usr/local/lib/python3.10/dist-packages/gemini/client.py](https://localhost:8080/#) in _set_cookies_from_file(self, file_path)
141 raise Exception(f"Failed to load cookies from {file_path}: {e}")
142
--> 143 self.session.cookies.update(cookies)
144
145 def _set_sid_and_nonce(self):
AttributeError: 'Gemini' object has no attribute 'session'
hello i`m have this issue
Exception: SNlM0e token value not found. Double-check cookies dict value or pass it as Gemini(cookies=Dict())
Describe the bug
ModuleNotFoundError: No module named 'gemini.src.module'
Version
OS: windows 11
Python: 3.12.2
Gemini API: 2.4.0
Using proxy: No
Legion: (i do not understand this)
Code
from gemini import Gemini
cookies_dict= #redacted
GeminiClient = Gemini(cookies=cookies_dict)
prompt = "Hello, Gemini. What's the weather like in Seoul today?"
response = GeminiClient.generate_content(prompt)
print(response.text)
Error
Traceback (most recent call last):
File "C:\Users\Ayush\Desktop\Project\jarvis\brain\bard.py", line 1, in <module>
from gemini import Gemini
File "C:\Users\Ayush\AppData\Local\Programs\Python\Python312\Lib\site-packages\gemini\__init__.py", line 5, in <module>
from .src.module.openrouter.client import OpenRouter
ModuleNotFoundError: No module named 'gemini.src.module'
After update to 1.0.0 i always see error 400 when i want to get response. All cookies are fresh and correct, code was work in 0.1.6
GeminiClient = Gemini(cookie_fp="cookies.json")
For this case instructions recommends ExportThisCookies, but does not mentioned that downloaded with it cookies.txt
is not real json: it is necessary to trim cookies =
to make it valid json.
But even with this I have no success:
Error loading cookie file: 'Gemini' object has no attribute 'session'
Traceback (most recent call last):
File "D:\AI\Gemini-API\test2.py", line 11, in <module>
GeminiClient = Gemini(cookie_fp="cookies.json") # Or use cookie file path
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\AI\Gemini-API\gemini\core.py", line 66, in __init__
self.session = session or self._initialize_session()
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\AI\Gemini-API\gemini\core.py", line 94, in _initialize_session
self._set_sid_and_nonce()
File "D:\AI\Gemini-API\gemini\core.py", line 213, in _set_sid_and_nonce
self._nonce = re.search(r'"SNlM0e":"(.*?)"', response.text).group(1)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'group'
GeminiClient = Gemini(cookies=cookies)
(where cookies are __Secure-1PSID
, __Secure-1PSIDTS
)
I get an output, but it is not very helpful:
{'metadata': ['c_409da1520e77ed5f', 'r_f3670ae69c52a4e1'], 'candidates': {'rcid': 'rc_594f1013ce897401', 'text': 'http://googleusercontent.com/card_content/0', 'web_images': [], 'generated_images': []}}
GeminiClient = Gemini(auto_cookies=True)
does not work:
Traceback (most recent call last):
File "D:\AI\Gemini-API\test.py", line 3, in <module>
GeminiClient = Gemini(auto_cookies=True)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\AI\Gemini-API\gemini\core.py", line 66, in __init__
self.session = session or self._initialize_session()
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\AI\Gemini-API\gemini\core.py", line 92, in _initialize_session
self._set_cookies_automatically()
File "D:\AI\Gemini-API\gemini\core.py", line 141, in _set_cookies_automatically
if len(getattr(self, "cookies", {})) > 5:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: object of type 'NoneType' has no len()
Originally posted by @johnd0e in #2 (comment)
The issue is still relevant for v2.2.0
Able to change model from Normal gemini to Advance.
i want to reuse previour chat session...i dont understant how to do it or how i can use rcid.please help me
Hello! In version 0.1.6, the response comes in the form of a string, but not in json format for further selection of the correct response. In addition, there are a lot of unnecessary special characters from the site layout.
Describe the bug
Gemini returns message "maximum recursion depth exceeded"
Version
OS: Ubuntu 23.10
Python: 3.11
Gemini API: 2.0.0
Using proxy: None
Legion:
Code
from gemini import Gemini
cookies = {} # I input my cookies here as decribe in README
GeminiClient = Gemini(cookies=cookies)
prompt = "hello, how are you?"
response = GeminiClient.generate_content(prompt)
print(response.response.dict)
Error
It returns "maximum recursion depth exceeded"
I check on gemini.google.com/app,
it has sent prompt to gemini but not get answer from gemini.google.com/app as below image
Bard API still runs smooth!
if i run a prompts it starting a new session..for that i can not ask anythg about previous question
Traceback (most recent call last):
File "c:\Users\Divyanshi\Desktop\New\app.py", line 22, in
GeminiClient = Gemini(cookies=cookies)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Divyanshi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\gemini\core.py", line 97, in init
self.token = self._get_snim0e()
^^^^^^^^^^^^^^^^^^
File "C:\Users\Divyanshi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\gemini\core.py", line 221, in _get_snim0e
raise Exception(
Exception: SNlM0e token value not found. Double-check cookies dict value or pass it as Gemini(cookies=Dict())
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()
from gemini import Gemini
from gemini import GeminiClient
async def main():
cookies = {
}
client = GeminiClient(cookies=cookies)
await client.async_init()
prompt = "Hello, Gemini. What's the weather like in Seoul today?"
response = client.generate_content(prompt)
print(response)
I know this is an "unofficial" api, but I'm wondering if there are any plans, or how hard it would be, to integrate this api with some visual programming platform, something like flowise, langflow or chainforge. I know these platforms wouldn't officially support this, but the code is open-source so it is possible. Any thoughts on this?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.