XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

Add streaming in openai chat Fetch access token with chromedriver

be9b8f79
Heiner Lohaus <heiner@lohaus.eu>
提交于

代码差异

2 个文件 +75 -24
Modified g4f/Provider/OpenaiChat.py +50 -23
@@ -1,14 +1,14 @@
1 1 from __future__ import annotations
2 2
3 from curl_cffi.requests import AsyncSession
4 3 import uuid
5 4 import json
6 5
7 from .base_provider import AsyncProvider, get_cookies, format_prompt
6 from .base_provider import AsyncGeneratorProvider
7 from .helper import get_browser, get_cookies, format_prompt
8 8 from ..typing import AsyncGenerator
9 from ..requests import StreamSession
9 10
10
11 class OpenaiChat(AsyncProvider):
11 class OpenaiChat(AsyncGeneratorProvider):
12 12 url = "https://chat.openai.com"
13 13 needs_auth = True
14 14 working = True
@@ -16,7 +16,7 @@ class OpenaiChat(AsyncProvider):
16 16 _access_token = None
17 17
18 18 @classmethod
19 async def create_async(
19 async def create_async_generator(
20 20 cls,
21 21 model: str,
22 22 messages: list[dict[str, str]],
@@ -32,7 +32,7 @@ class OpenaiChat(AsyncProvider):
32 32 "Accept": "text/event-stream",
33 33 "Authorization": f"Bearer {access_token}",
34 34 }
35 async with AsyncSession(proxies=proxies, headers=headers, impersonate="chrome107") as session:
35 async with StreamSession(proxies=proxies, headers=headers, impersonate="chrome107") as session:
36 36 messages = [
37 37 {
38 38 "id": str(uuid.uuid4()),
@@ -48,31 +48,58 @@ class OpenaiChat(AsyncProvider):
48 48 "model": "text-davinci-002-render-sha",
49 49 "history_and_training_disabled": True,
50 50 }
51 response = await session.post("https://chat.openai.com/backend-api/conversation", json=data)
52 response.raise_for_status()
53 last_message = None
54 for line in response.content.decode().splitlines():
55 if line.startswith("data: "):
56 line = line[6:]
57 if line == "[DONE]":
58 break
59 line = json.loads(line)
60 if "message" in line:
61 last_message = line["message"]["content"]["parts"][0]
62 return last_message
51 async with session.post(f"{cls.url}/backend-api/conversation", json=data) as response:
52 response.raise_for_status()
53 last_message = ""
54 async for line in response.iter_lines():
55 if line.startswith(b"data: "):
56 line = line[6:]
57 if line == b"[DONE]":
58 break
59 line = json.loads(line)
60 if "message" in line and not line["message"]["end_turn"]:
61 new_message = line["message"]["content"]["parts"][0]
62 yield new_message[len(last_message):]
63 last_message = new_message
64
65 @classmethod
66 def fetch_access_token(cls) -> str:
67 try:
68 from selenium.webdriver.common.by import By
69 from selenium.webdriver.support.ui import WebDriverWait
70 from selenium.webdriver.support import expected_conditions as EC
71 except ImportError:
72 return
63 73
74 driver = get_browser()
75 if not driver:
76 return
77
78 driver.get(f"{cls.url}/")
79 try:
80 WebDriverWait(driver, 1200).until(
81 EC.presence_of_element_located((By.ID, "prompt-textarea"))
82 )
83 javascript = "return (await (await fetch('/api/auth/session')).json())['accessToken']"
84 return driver.execute_script(javascript)
85 finally:
86 driver.quit()
64 87
65 88 @classmethod
66 89 async def get_access_token(cls, cookies: dict = None, proxies: dict = None) -> str:
67 90 if not cls._access_token:
68 91 cookies = cookies if cookies else get_cookies("chat.openai.com")
69 async with AsyncSession(proxies=proxies, cookies=cookies, impersonate="chrome107") as session:
70 response = await session.get("https://chat.openai.com/api/auth/session")
71 response.raise_for_status()
72 cls._access_token = response.json()["accessToken"]
92 async with StreamSession(proxies=proxies, cookies=cookies, impersonate="chrome107") as session:
93 async with session.get(f"{cls.url}/api/auth/session") as response:
94 response.raise_for_status()
95 auth = await response.json()
96 if "accessToken" in auth:
97 cls._access_token = auth["accessToken"]
98 cls._access_token = cls.fetch_access_token()
99 if not cls._access_token:
100 raise RuntimeError("Missing access token")
73 101 return cls._access_token
74 102
75
76 103 @classmethod
77 104 @property
78 105 def params(cls):
Modified g4f/Provider/helper.py +25 -1
@@ -56,4 +56,28 @@ def format_prompt(messages: list[dict[str, str]], add_special_tokens=False):
56 56 )
57 57 return f"{formatted}\nAssistant:"
58 58 else:
59 return messages[0]["content"]
59 return messages[0]["content"]
60
61
62 def get_browser(user_data_dir: str = None):
63 try:
64 from undetected_chromedriver import Chrome
65 except ImportError:
66 return None
67
68 def get_user_data_dir():
69 dirs = [
70 '~/.config/google-chrome/Default',
71 '~/.var/app/com.google.Chrome/config/google-chrome/Default',
72 '%LOCALAPPDATA%\\Google\\Chrome\\User Data\\Default',
73 '~/Library/Application Support/Google/Chrome/Default',
74 ]
75 from os import path
76 for dir in dirs:
77 dir = path.expandvars(dir)
78 if path.exists(dir):
79 return dir
80 if not user_data_dir:
81 user_data_dir = get_user_data_dir()
82
83 return Chrome(user_data_dir=user_data_dir)