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

XFEstudio/gpt4free

Close cdp relay

6d558935
hlohaus <983577+hlohaus@users.noreply.github.com>
提交于

代码差异

6 个文件 +90 -36
Modified g4f/Provider/__init__.py +7 -0
@@ -361,6 +361,7 @@ class ProviderLoader:
361 361
362 362 return OpenAIFM
363 363 elif name == "OpenCode":
364 import time
364 365 from ..client.factory import AbstractClientFactory
365 366 cls.loaded[name] = AbstractClientFactory.create_provider(
366 367 None, "https://opencode.ai/zen/v1"
@@ -369,6 +370,12 @@ class ProviderLoader:
369 370 cls.loaded[name].url = "https://opencode.ai"
370 371 cls.loaded[name].active_by_default = True
371 372 cls.loaded[name].default_model = "big-pickle"
373 cls.loaded[name].headers = {
374 "Content-Type": "application/json",
375 "User-Agent": "opencode/1.18.31 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14",
376 "x-session-affinity": f"ses_{int(time.time())}",
377 "x-session-id": f"ses_{int(time.time())}",
378 }
372 379 return cls.loaded[name]
373 380
374 381 elif name == "OpenRouter":
Modified g4f/Provider/search/GoogleAiMode.py +22 -7
@@ -37,13 +37,13 @@ class GoogleAiMode(GoogleSearch):
37 37
38 38 try:
39 39 await session.navigate(search_url)
40 await session.click_accept_button()
40 await session.click_accept_button(False)
41 41 except Exception as e:
42 42 await session.close()
43 43 raise e
44 44
45 45 try:
46 await session.wait_for_network_idle(idle_time=1, timeout=10.0)
46 await session.wait_for_network_idle()
47 47 search_results = await cls._read_search_results(session)
48 48 if search_results:
49 49 yield SearchResults(search_results)
@@ -55,7 +55,7 @@ class GoogleAiMode(GoogleSearch):
55 55
56 56 try:
57 57 for _ in range(5):
58 await session.evaluate_js("""const b = Array.from(document.querySelectorAll("a, button")).filter(a => {
58 await session.evaluate_js("""b = Array.from(document.querySelectorAll("a, button")).filter(a => {
59 59 return a.textContent.endsWith("KI‑Modus") || a.textContent.endsWith("AI Mode");
60 60 }).pop(); b ? b.click() : null; !!b""")
61 61 await session.wait_for_network_idle(idle_time=1, timeout=10.0)
@@ -64,26 +64,41 @@ const rootElement = document.querySelector('[decode-data-ved="1"]');
64 64 function getTextNodes(element) {
65 65 const textNodes = [];
66 66 for (const child of element.childNodes) {
67 if (child.nodeType === Node.ELEMENT_NODE && child.tagName === "STRONG") {
68 textNodes.push("**");
69 }
67 70 if (child.nodeType === Node.TEXT_NODE && child.textContent) {
68 textNodes.push(child);
71 textNodes.push(child.textContent);
69 72 } else {
70 73 textNodes.push(...getTextNodes(child));
71 74 }
75 if (child.nodeType === Node.ELEMENT_NODE && child.tagName === "STRONG") {
76 textNodes.push("**");
77 }
78 if (child.nodeType === Node.ELEMENT_NODE && child.tagName === "DIV") {
79 if (child.parentElement && child.parentElement.tagName !== "DIV") {
80 textNodes.push("\\n");
81 }
82 }
72 83 }
73 84 return textNodes;
74 85 }
75 86 const allTexts = [];
76 for (const text of getTextNodes(rootElement).map(node => node.textContent)) {
87 for (const text of getTextNodes(rootElement)) {
77 88 if (text.includes("KI-Antworten können Fehler enthalten.") || text.includes("AI responses may include mistakes.")) {
78 89 break;
79 90 }
80 91 allTexts.push(text);
81 92 }
82 93 allTexts;""");
83 debug.log(f"Google Search: AI mode results: {result}")
84 94 if result:
95 first = True
85 96 for text in result:
86 yield f"{text}\n"
97 if first:
98 first = False
99 debug.log(f"Google AI Mode: {text}")
100 else:
101 yield text
87 102 return
88 103 raise RuntimeError("No AI mode results found.")
89 104 finally:
Modified g4f/Provider/template/OpenaiTemplate.py +4 -1
@@ -34,6 +34,9 @@ class OpenaiTemplate(AsyncGeneratorProvider, ProviderModelMixin, RaiseErrorMixin
34 34 supports_native_tools: bool = True
35 35 _checked_api_keys: dict = {}
36 36 add_thought_signature = None
37 headers = {
38 "Content-Type": "application/json"
39 }
37 40
38 41 @classmethod
39 42 async def get_quota(cls, api_key: Optional[str] = None, **kwargs) -> dict:
@@ -366,7 +369,7 @@ class OpenaiTemplate(AsyncGeneratorProvider, ProviderModelMixin, RaiseErrorMixin
366 369 ) -> dict:
367 370 return {
368 371 "Accept": "text/event-stream" if stream else "application/json",
369 "Content-Type": "application/json",
372 **cls.headers,
370 373 **({"Authorization": f"Bearer {api_key}"} if api_key else {}),
371 374 **({} if headers is None else headers),
372 375 }
Modified g4f/api/__init__.py +9 -6
@@ -599,11 +599,13 @@ class ErrorResponse(Response):
599 599
600 600
601 601 def update_headers(
602 request: Request, user: str = None
602 request: Request, user: str = None, remove_authorization_header: bool = False
603 603 ) -> Request:
604 604 new_headers = request.headers.mutablecopy()
605 605 if user:
606 606 new_headers["x-user"] = user
607 if remove_authorization_header and "authorization" in new_headers:
608 del new_headers["authorization"]
607 609 request.scope["headers"] = new_headers.raw
608 610 delattr(request, "_headers")
609 611 return request
@@ -649,6 +651,7 @@ class Api:
649 651 @self.app.middleware("http")
650 652 async def authorization(request: Request, call_next):
651 653 user = None
654 remove_authorization_header = False
652 655 if (
653 656 request.method != "OPTIONS"
654 657 and AppConfig.g4f_api_key is not None
@@ -659,24 +662,24 @@ class Api:
659 662 user_g4f_api_key = getattr(
660 663 await self.security(request), "credentials", None
661 664 )
662 if user_g4f_api_key:
663 user_g4f_api_key = user_g4f_api_key.split()
665 remove_authorization_header = True
664 666 if (
665 667 AppConfig.g4f_api_key is None
666 668 or not user_g4f_api_key
667 669 or not secrets.compare_digest(
668 AppConfig.g4f_api_key, user_g4f_api_key[0]
670 AppConfig.g4f_api_key, user_g4f_api_key
669 671 )
670 672 ):
671 673 try:
672 674 new_user = await self.get_username(request)
673 675 if user is None:
676 remove_authorization_header = True
674 677 user = new_user
675 678 except HTTPException as e:
676 679 return ErrorResponse.from_message(
677 680 e.detail, e.status_code, e.headers
678 681 )
679 request = update_headers(request, user)
682 request = update_headers(request, user, remove_authorization_header)
680 683 response = await call_next(request)
681 684 return response
682 685
@@ -897,7 +900,7 @@ class Api:
897 900 ] = None,
898 901 mode: str | None = None,
899 902 provider: str | None = None,
900 model: str | None = None,
903 conversation_id: str | None = None,
901 904 x_user: Annotated[str | None, Header()] | None = None,
902 905 ):
903 906 if mode == "raw":
Modified g4f/models.py +1 -0
@@ -133,6 +133,7 @@ default = Model(
133 133 "KiloCode",
134 134 "OpenRouterFree",
135 135 "GeminiPro",
136 "LLM7"
136 137 ]
137 138 ),
138 139 )
Modified g4f/requests/cdp.py +47 -22
@@ -439,6 +439,9 @@ class CDPSession:
439 439 self._event_queues: Dict[str, List[asyncio.Queue]] = {}
440 440 self._closing = False
441 441 self._connection_lost = False
442 # True when this session runs through the browser-extension relay
443 # (g4f/api/cdp_relay.py) instead of a local Chrome CDP port.
444 self._via_extension = False
442 445
443 446 # Network event loggers
444 447 self.network_requests: List[dict] = []
@@ -567,6 +570,7 @@ class CDPSession:
567 570 raise RuntimeError("CDP relay: failed to create extension tab")
568 571
569 572 self.target_id = target_id
573 self._via_extension = True
570 574
571 575 # 2. Connect to the relay's pass-through WebSocket for this target.
572 576 ws_url = f"ws://{api_host}:{api_port}/v1/cdp/ws/{quote_plus(target_id)}"
@@ -680,6 +684,8 @@ class CDPSession:
680 684 res = await self.call(
681 685 "Runtime.evaluate", expression=expression, returnByValue=True
682 686 )
687 if "result" not in res or "value" not in res["result"]:
688 raise RuntimeError(f"JavaScript evaluation failed: {res}")
683 689 return res.get("result", {}).get("value")
684 690
685 691 async def get_cookies(self) -> dict:
@@ -875,14 +881,9 @@ class CDPSession:
875 881 logger.debug(f"Failed to include debug script: {e}")
876 882 return False
877 883
878 async def click_accept_button(self) -> bool:
884 async def click_accept_button(self, do_submit: bool = True) -> bool:
879 885 """Find and click an 'Accept' or 'Einwilligen' button, including inside iframes."""
880 886 js_code = """
881 // 1. Inject debug script to show logging
882 const debugEl = document.createElement('script');
883 debugEl.src = 'https://g4f.dev/dist/js/debug.js';
884 document.head.appendChild(debugEl);
885
886 887 // 2. Get the current URL's search parameters
887 888 const params = new URLSearchParams(window.location.search || document.location.hash.substring(1));
888 889 const searchQuery = params.get('q');
@@ -943,16 +944,28 @@ const acceptBtns = (() => {
943 944
944 945 return searchDocument(document, window.scrollX, window.scrollY);
945 946 })();
947 const clickedTexts = [];
946 948 if (acceptBtns && acceptBtns.length > 0) {
947 949 acceptBtns.forEach(btn => {
948 950 try {
949 951 btn.click();
952 clickedTexts.push(btn.innerText || btn.value || btn.textContent || '');
950 953 } catch (e) {
951 954 console.error('Failed to click accept button:', e);
952 955 }
953 956 });
954 957 }
955
958 clickedTexts.join(', ');
959 """
960 try:
961 rect = await self.evaluate_js(js_code)
962 if rect and isinstance(rect, str):
963 debug.log(f"Clicked button with text: {rect}")
964 except Exception as e:
965 debug.log(f"Failed to click accept button: {e}")
966 if not do_submit:
967 return bool(rect)
968 js_code = """
956 969 // 4. Enable Google AI Mode if the URL has the ai-mode parameter
957 970 let googleAiModeButton = null;
958 971 function enableGoogleAiMode() {
@@ -1052,15 +1065,12 @@ if (deepseekSendButton) {
1052 1065
1053 1066 // 9. Return the text content of the first found send button for logging/debugging
1054 1067 (
1055 sendButton || geminiSendButton || deepseekSendButton || (acceptBtns && acceptBtns[0]) || googleAiModeButton
1068 sendButton || geminiSendButton || deepseekSendButton || googleAiModeButton
1056 1069 )?.textContent.trim();
1057 1070 """
1058 1071 try:
1059 1072 rect = await self.evaluate_js(js_code)
1060 if rect and isinstance(rect, list) and len(rect) == 2:
1061 await self.click(int(rect[0]), int(rect[1]))
1062 return True
1063 elif rect and isinstance(rect, str):
1073 if rect and isinstance(rect, str):
1064 1074 debug.log(f"Clicked button with text: {rect}")
1065 1075 return True
1066 1076 except Exception as e:
@@ -1231,15 +1241,30 @@ if (deepseekSendButton) {
1231 1241 await self.session.close()
1232 1242 self.session = None
1233 1243
1234 if self.target_id and self.port:
1235 try:
1236 urllib.request.urlopen(
1237 f"http://{self.host}:{self.port}/json/close/{self.target_id}",
1238 timeout=2,
1239 )
1240 except Exception:
1241 pass
1244 if self.target_id:
1245 if self._via_extension:
1246 # Extension mode: ask the relay to close the automation tab
1247 # in the extension's browser (agent executes close_tab).
1248 try:
1249 api_host = os.environ.get("G4F_API_HOST", "127.0.0.1")
1250 api_port = os.environ.get("G4F_API_PORT", "1337")
1251 urllib.request.urlopen(
1252 f"http://{api_host}:{api_port}/json/close/{self.target_id}",
1253 timeout=5,
1254 )
1255 except Exception:
1256 pass
1257 elif self.port:
1258 try:
1259 urllib.request.urlopen(
1260 f"http://{self.host}:{self.port}/json/close/{self.target_id}",
1261 timeout=2,
1262 )
1263 except Exception:
1264 pass
1242 1265 self.target_id = None
1243 1266
1244 # Release our tab; browser stays alive for reuse by other tabs
1245 release_shared_browser_ref()
1267 # Release our tab; browser stays alive for reuse by other tabs.
1268 # Extension mode never acquired a shared-browser reference.
1269 if not self._via_extension:
1270 release_shared_browser_ref()