From 5b2efa4aaf00cb5b5b169c83f2690630495a962e Mon Sep 17 00:00:00 2001 From: Heiner Lohaus Date: Tue, 3 Oct 2023 23:53:17 +0200 Subject: Fix fetch_access_token in openai --- g4f/Provider/OpenaiChat.py | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) (limited to 'g4f') diff --git a/g4f/Provider/OpenaiChat.py b/g4f/Provider/OpenaiChat.py index fbd26d7c..ca148da2 100644 --- a/g4f/Provider/OpenaiChat.py +++ b/g4f/Provider/OpenaiChat.py @@ -63,7 +63,7 @@ class OpenaiChat(AsyncGeneratorProvider): last_message = new_message @classmethod - def fetch_access_token(cls) -> str: + def browse_access_token(cls) -> str: try: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait @@ -85,19 +85,25 @@ class OpenaiChat(AsyncGeneratorProvider): finally: driver.quit() + @classmethod + async def fetch_access_token(cls, cookies: dict, proxies: dict = None) -> str: + async with StreamSession(proxies=proxies, cookies=cookies, impersonate="chrome107") as session: + async with session.get(f"{cls.url}/api/auth/session") as response: + response.raise_for_status() + auth = await response.json() + if "accessToken" in auth: + return auth["accessToken"] + @classmethod async def get_access_token(cls, cookies: dict = None, proxies: dict = None) -> str: if not cls._access_token: cookies = cookies if cookies else get_cookies("chat.openai.com") - async with StreamSession(proxies=proxies, cookies=cookies, impersonate="chrome107") as session: - async with session.get(f"{cls.url}/api/auth/session") as response: - response.raise_for_status() - auth = await response.json() - if "accessToken" in auth: - cls._access_token = auth["accessToken"] - cls._access_token = cls.fetch_access_token() - if not cls._access_token: - raise RuntimeError("Missing access token") + if cookies: + cls._access_token = await cls.fetch_access_token(cookies, proxies) + if not cls._access_token: + cls._access_token = cls.browse_access_token() + if not cls._access_token: + raise RuntimeError("Read access token failed") return cls._access_token @classmethod -- cgit v1.2.3