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

XFEstudio/gpt4free

Update HuggingChat authentication flow and improve error handling; add image and audio templates in tools

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

代码差异

3 个文件 +25 -31
Modified g4f/Provider/needs_auth/hf/HuggingChat.py +9 -17
@@ -1,11 +1,9 @@
1 1 from __future__ import annotations
2 2
3 3 import json
4 import re
5 4 import os
6 5 import requests
7 6 import base64
8 import uuid
9 7 from typing import AsyncIterator
10 8
11 9 try:
@@ -37,7 +35,7 @@ class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
37 35 origin = f"https://{domain}"
38 36 url = f"{origin}/chat"
39 37
40 working = False
38 working = True
41 39 use_nodriver = True
42 40 supports_stream = True
43 41 needs_auth = True
@@ -64,27 +62,18 @@ class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
64 62 async def on_auth_async(cls, cookies: Cookies = None, proxy: str = None, **kwargs) -> AsyncIterator:
65 63 if cookies is None:
66 64 cookies = get_cookies(cls.domain, single_browser=True)
67 if "hf-chat" in cookies:
68 yield AuthResult(
69 cookies=cookies,
70 headers=DEFAULT_HEADERS,
71 impersonate="chrome"
72 )
73 return
74 if cls.needs_auth:
65 try:
75 66 yield RequestLogin(cls.__name__, os.environ.get("G4F_LOGIN_URL") or "")
76 67 yield AuthResult(
77 68 **await get_args_from_nodriver(
78 69 cls.url,
79 70 proxy=proxy,
80 wait_for='form[action$="/logout"]'
71 wait_for='div div nav div div img'
81 72 )
82 73 )
83 else:
74 except MissingRequirementsError:
84 75 yield AuthResult(
85 cookies={
86 "hf-chat": str(uuid.uuid4()) # Generate a session ID
87 },
76 cookies=cookies,
88 77 headers=DEFAULT_HEADERS,
89 78 impersonate="chrome"
90 79 )
@@ -198,7 +187,10 @@ class HuggingChat(AsyncAuthedProvider, ProviderModelMixin):
198 187 if response.status_code == 400:
199 188 raise ResponseError(f"{response.text}: Model: {model}")
200 189 raise_for_status(response)
201 return response.json().get('conversationId')
190 try:
191 return response.json().get('conversationId')
192 except json.JSONDecodeError as e:
193 raise MissingAuthError(f"Failed to decode JSON: {e}") from e
202 194
203 195 @classmethod
204 196 def fetch_message_id(cls, session: Session, conversation_id: str):
Modified g4f/gui/server/website.py +2 -1
@@ -19,11 +19,13 @@ def render(filename = "home", download_url: str = GITHUB_URL):
19 19 if download_url == GITHUB_URL:
20 20 filename += ("" if "." in filename else ".html")
21 21 html = None
22 is_temp = False
22 23 if os.path.exists(DIST_DIR) and not request.args.get("debug"):
23 24 path = os.path.abspath(os.path.join(os.path.dirname(DIST_DIR), filename))
24 25 if os.path.exists(path):
25 26 if download_url == GITHUB_URL:
26 27 html = open(path, 'r', encoding='utf-8').read()
28 is_temp = True
27 29 else:
28 30 return send_from_directory(os.path.dirname(path), os.path.basename(path))
29 31 try:
@@ -34,7 +36,6 @@ def render(filename = "home", download_url: str = GITHUB_URL):
34 36 cache_dir = os.path.join(get_cookies_dir(), ".gui_cache", today)
35 37 latest_version = str(latest_version) +quote(unquote(request.query_string.decode())) or str(latest_version)
36 38 cache_file = os.path.join(cache_dir, f"{secure_filename(f'{version.utils.current_version}-{latest_version}')}.{secure_filename(filename)}")
37 is_temp = False
38 39 if os.path.isfile(cache_file + ".js"):
39 40 cache_file += ".js"
40 41 if not os.path.exists(cache_file):
Modified g4f/mcp/tools.py +14 -13
@@ -10,6 +10,7 @@ from __future__ import annotations
10 10
11 11 from typing import Any, Dict
12 12 from abc import ABC, abstractmethod
13 import urllib.parse
13 14
14 15 from aiohttp import ClientSession
15 16
@@ -269,6 +270,8 @@ class ImageGenerationTool(MCPTool):
269 270 }
270 271
271 272 image_url = image_data.url
273
274 template = 'Display the image using this template: <a href="{image}" data-width="{width}" data-height="{height}"><img src="{image}" alt="{prompt}"></a>'
272 275
273 276 # Return result based on URL type
274 277 if image_url.startswith('data:'):
@@ -277,7 +280,8 @@ class ImageGenerationTool(MCPTool):
277 280 "model": model,
278 281 "width": width,
279 282 "height": height,
280 "image": image_url
283 "image": image_url,
284 "template": template
281 285 }
282 286 else:
283 287 if arguments.get("origin") and image_url.startswith("/media/"):
@@ -287,7 +291,8 @@ class ImageGenerationTool(MCPTool):
287 291 "model": model,
288 292 "width": width,
289 293 "height": height,
290 "image_url": image_url
294 "image_url": image_url,
295 "template": template
291 296 }
292 297
293 298 except Exception as e:
@@ -411,13 +416,6 @@ class TextToAudioTool(MCPTool):
411 416 Returns:
412 417 Dict[str, Any]: Audio URL or error message
413 418 """
414 try:
415 import urllib.parse
416 except ImportError as e:
417 return {
418 "error": f"urllib is not available: {str(e)}"
419 }
420
421 419 prompt = arguments.get("prompt", "")
422 420 voice = arguments.get("voice", "alloy")
423 421 url_encode = arguments.get("url_encode", True)
@@ -428,9 +426,9 @@ class TextToAudioTool(MCPTool):
428 426 }
429 427
430 428 # Validate prompt length (reasonable limit for text-to-speech)
431 if len(prompt) > 5000:
429 if len(prompt) > 10000:
432 430 return {
433 "error": "Prompt is too long (max 5000 characters)"
431 "error": "Prompt is too long (max 10000 characters)"
434 432 }
435 433
436 434 try:
@@ -441,18 +439,21 @@ class TextToAudioTool(MCPTool):
441 439 encoded_prompt = prompt.replace(" ", "%20") # Basic space encoding
442 440
443 441 # Construct the Pollinations AI text-to-speech URL
444 audio_url = f"/backend-api/v2/create?provider=Gemini&model=gemini-audio&cache=true&prompt={encoded_prompt}"
442 audio_url = f"/backend-api/v2/synthesize/Gemini?text={encoded_prompt}"
445 443
446 444 if arguments.get("origin"):
447 445 audio_url = f"{arguments.get('origin')}{audio_url}"
448 446 async with ClientSession() as session:
449 447 async with session.get(audio_url, max_redirects=0) as resp:
450 448 audio_url = str(resp.url)
449
450 template = 'Play the audio using this template: <audio controls src="{audio_url}">'
451 451
452 452 return {
453 453 "prompt": prompt,
454 454 "voice": voice,
455 "audio_url": audio_url
455 "audio_url": audio_url,
456 "template": template
456 457 }
457 458
458 459 except Exception as e: