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

XFEstudio/gpt4free

Update EasyChat and OpenRouter classes, modify backend API timing, and enhance website rendering

7c5ec532
hlohaus <983577+hlohaus@users.noreply.github.com>
提交于

代码差异

5 个文件 +38 -49
Modified g4f/Provider/EasyChat.py +3 -3
@@ -21,7 +21,7 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
21 21 url = "https://chat3.eqing.tech"
22 22 api_base = f"{url}/api/openai/v1"
23 23 api_endpoint = f"{api_base}/chat/completions"
24 working = True
24 working = False
25 25 active_by_default = True
26 26 use_model_names = True
27 27
@@ -55,7 +55,7 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
55 55 **kwargs
56 56 ) -> AsyncResult:
57 57 cls.share_url = os.getenv("G4F_SHARE_URL")
58 model = cls.get_model(model)
58 model = cls.get_model(model.replace("-free", ""))
59 59 args = None
60 60 cache_file = cls.get_cache_file()
61 61 async def callback(page):
@@ -84,7 +84,7 @@ class EasyChat(OpenaiTemplate, AuthFileMixin):
84 84 if cls.captchaToken:
85 85 debug.log("EasyChat: Captcha token found, proceeding.")
86 86 break
87 textarea = await page.select("textarea", 180)
87 textarea = await page.select("[contenteditable=\"true\"]", 180)
88 88 if textarea is not None:
89 89 await textarea.send_keys("Hello")
90 90 await asyncio.sleep(1)
Modified g4f/Provider/needs_auth/OpenRouter.py +7 -4
@@ -18,10 +18,13 @@ class OpenRouterFree(OpenRouter):
18 18
19 19 @classmethod
20 20 def get_models(cls, api_key: str = None, **kwargs):
21 models = super().get_models(api_key=api_key, **kwargs)
22 models = [model for model in models if model.endswith(":free") or model.endswith("/auto")]
23 cls.model_aliases = {model.replace(":free", ""): model for model in models}
24 return [model.replace(":free", "") for model in models]
21 if not cls.models:
22 models = super().get_models(api_key=api_key, **kwargs)
23 models = [model for model in models if model.endswith(":free")]
24 cls.model_aliases = {model.replace(":free", ""): model for model in models}
25 cls.models = [model.replace(":free", "") for model in models]
26 cls.default_model = models[0] if models else cls.default_model
27 return cls.models
25 28
26 29 @classmethod
27 30 def get_model(cls, model: str, **kwargs) -> str:
Modified g4f/config.py +2 -1
@@ -25,4 +25,5 @@ STATIC_DOMAIN = f"{PACKAGE_NAME}.dev"
25 25 STATIC_URL = f"https://{STATIC_DOMAIN}/"
26 26 DIST_DIR = f"./{STATIC_DOMAIN}/dist"
27 27 DOWNLOAD_URL = f"https://raw.githubusercontent.com/{ORGANIZATION}/{STATIC_DOMAIN}/refs/heads/main/"
28 DEFAULT_MODEL = "openai/gpt-oss-120b"
28 DEFAULT_MODEL = "openai/gpt-oss-120b"
29 JSDELIVR_URL = "https://cdn.jsdelivr.net/"
Modified g4f/gui/server/backend_api.py +1 -33
@@ -102,7 +102,7 @@ class Backend_Api(Api):
102 102 try:
103 103 decrypted_secret = decrypt_data(sub_private_key, decrypt_data(private_key_obj, secret))
104 104 timediff = time.time() - int(decrypted_secret)
105 return timediff <= 3 and timediff >= 0
105 return timediff <= 5 and timediff >= 0
106 106 except Exception as e:
107 107 logger.error(f"Secret validation failed: {e}")
108 108 return False
@@ -247,38 +247,6 @@ class Backend_Api(Api):
247 247 f.write(f"{json.dumps(data)}\n")
248 248 return {}
249 249
250 @app.route('/backend-api/v2/memory/<user_id>', methods=['POST'])
251 def add_memory(user_id: str):
252 api_key = request.headers.get("x_api_key")
253 json_data = request.json
254 from mem0 import MemoryClient
255 client = MemoryClient(api_key=api_key)
256 client.add(
257 [{"role": item["role"], "content": item["content"]} for item in json_data.get("items")],
258 user_id=user_id,
259 metadata={"conversation_id": json_data.get("id")}
260 )
261 return {"count": len(json_data.get("items"))}
262
263 @app.route('/backend-api/v2/memory/<user_id>', methods=['GET'])
264 def read_memory(user_id: str):
265 api_key = request.headers.get("x_api_key")
266 from mem0 import MemoryClient
267 client = MemoryClient(api_key=api_key)
268 if request.args.get("search"):
269 return client.search(
270 request.args.get("search"),
271 user_id=user_id,
272 filters=json.loads(request.args.get("filters", "null")),
273 metadata=json.loads(request.args.get("metadata", "null"))
274 )
275 return client.get_all(
276 user_id=user_id,
277 page=request.args.get("page", 1),
278 page_size=request.args.get("page_size", 100),
279 filters=json.loads(request.args.get("filters", "null")),
280 )
281
282 250 self.routes = {
283 251 '/backend-api/v2/synthesize/<provider>': {
284 252 'function': self.handle_synthesize,
Modified g4f/gui/server/website.py +25 -8
@@ -8,31 +8,33 @@ from flask import send_from_directory, redirect, request
8 8 from ...image.copy_images import secure_filename
9 9 from ...cookies import get_cookies_dir
10 10 from ...errors import VersionNotFoundError
11 from ...config import STATIC_URL, DOWNLOAD_URL, DIST_DIR
11 from ...config import STATIC_URL, DOWNLOAD_URL, DIST_DIR, JSDELIVR_URL
12 12 from ... import version
13 13
14 14 def redirect_home():
15 15 return redirect('/chat/')
16 16
17 def render(filename = "home"):
18 filename += ("" if "." in filename else ".html")
17 def render(filename = "home", download_url: str = DOWNLOAD_URL):
18 if download_url == DOWNLOAD_URL:
19 filename += ("" if "." in filename else ".html")
19 20 if os.path.exists(DIST_DIR) and not request.args.get("debug"):
20 21 path = os.path.abspath(os.path.join(os.path.dirname(DIST_DIR), filename))
21 return send_from_directory(os.path.dirname(path), os.path.basename(path))
22 if os.path.exists(path):
23 return send_from_directory(os.path.dirname(path), os.path.basename(path))
22 24 try:
23 25 latest_version = version.utils.latest_version
24 26 except VersionNotFoundError:
25 27 latest_version = version.utils.current_version
26 28 today = datetime.today().strftime('%Y-%m-%d')
27 cache_dir = os.path.join(get_cookies_dir(), ".gui_cache")
28 cache_file = os.path.join(cache_dir, f"{secure_filename(filename)}.{today}.{secure_filename(f'{version.utils.current_version}-{latest_version}')}.html")
29 cache_dir = os.path.join(get_cookies_dir(), ".gui_cache", today)
30 cache_file = os.path.join(cache_dir, f"{secure_filename(f'{version.utils.current_version}-{latest_version}')}.{secure_filename(filename)}")
29 31 is_temp = False
30 32 if not os.path.exists(cache_file):
31 33 if os.access(cache_file, os.W_OK):
32 34 is_temp = True
33 35 else:
34 36 os.makedirs(cache_dir, exist_ok=True)
35 response = requests.get(f"{DOWNLOAD_URL}{filename}")
37 response = requests.get(f"{download_url}{filename}")
36 38 if not response.ok:
37 39 found = None
38 40 for root, _, files in os.walk(cache_dir):
@@ -45,6 +47,7 @@ def render(filename = "home"):
45 47 else:
46 48 response.raise_for_status()
47 49 html = response.text
50 html = html.replace(JSDELIVR_URL, "")
48 51 html = html.replace("../dist/", f"dist/")
49 52 html = html.replace("\"dist/", f"\"{STATIC_URL}dist/")
50 53 if is_temp:
@@ -85,6 +88,14 @@ class Website:
85 88 'function': self._dist,
86 89 'methods': ['GET']
87 90 },
91 '/gh/<path:name>': {
92 'function': self._gh,
93 'methods': ['GET']
94 },
95 '/npm/<path:name>': {
96 'function': self._npm,
97 'methods': ['GET']
98 },
88 99 }
89 100
90 101 def _index(self, filename = "home"):
@@ -101,4 +112,10 @@ class Website:
101 112 return render(filename)
102 113
103 114 def _dist(self, name: str):
104 return send_from_directory(os.path.abspath(DIST_DIR), name)
115 return send_from_directory(os.path.abspath(DIST_DIR), name)
116
117 def _gh(self, name):
118 return render(f"gh/{name}", JSDELIVR_URL)
119
120 def _npm(self, name):
121 return render(f"npm/{name}", JSDELIVR_URL)