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

XFEstudio/gpt4free

Fix: There is no current event loop in thread

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

代码差异

5 个文件 +41 -27
Modified g4f/Provider/AItianhu.py +25 -11
@@ -1,24 +1,25 @@
1 1 from __future__ import annotations
2 2
3 3 import json
4 from curl_cffi.requests import AsyncSession
5 4
6 from .base_provider import AsyncProvider, format_prompt
5 from ..typing import AsyncGenerator
6 from ..requests import StreamSession
7 from .base_provider import AsyncGeneratorProvider, format_prompt
7 8
8 9
9 class AItianhu(AsyncProvider):
10 class AItianhu(AsyncGeneratorProvider):
10 11 url = "https://www.aitianhu.com"
11 12 working = True
12 13 supports_gpt_35_turbo = True
13 14
14 15 @classmethod
15 async def create_async(
16 async def create_async_generator(
16 17 cls,
17 18 model: str,
18 19 messages: list[dict[str, str]],
19 20 proxy: str = None,
20 21 **kwargs
21 ) -> str:
22 ) -> AsyncGenerator:
22 23 data = {
23 24 "prompt": format_prompt(messages),
24 25 "options": {},
@@ -27,12 +28,25 @@ class AItianhu(AsyncProvider):
27 28 "top_p": 1,
28 29 **kwargs
29 30 }
30 async with AsyncSession(proxies={"https": proxy}, impersonate="chrome107", verify=False) as session:
31 response = await session.post(cls.url + "/api/chat-process", json=data)
32 response.raise_for_status()
33 line = response.text.splitlines()[-1]
34 line = json.loads(line)
35 return line["text"]
31 headers = {
32 "Authority": cls.url,
33 "Accept": "application/json, text/plain, */*",
34 "Origin": cls.url,
35 "Referer": f"{cls.url}/"
36 }
37 async with StreamSession(headers=headers, proxies={"https": proxy}, impersonate="chrome107", verify=False) as session:
38 async with session.post(f"{cls.url}/api/chat-process", json=data) as response:
39 response.raise_for_status()
40 async for line in response.iter_lines():
41 if b"platform's risk control" in line:
42 raise RuntimeError("Platform's Risk Control")
43 line = json.loads(line)
44 if "detail" in line:
45 content = line["detail"]["choices"][0]["delta"].get("content")
46 if content:
47 yield content
48 else:
49 raise RuntimeError(f"Response: {line}")
36 50
37 51
38 52 @classmethod
Modified g4f/Provider/AItianhuSpace.py +2 -1
@@ -2,6 +2,7 @@ from __future__ import annotations
2 2
3 3 import random, json
4 4
5 from ..typing import AsyncGenerator
5 6 from ..requests import StreamSession
6 7 from .base_provider import AsyncGeneratorProvider, format_prompt
7 8
@@ -22,7 +23,7 @@ class AItianhuSpace(AsyncGeneratorProvider):
22 23 messages: list[dict[str, str]],
23 24 stream: bool = True,
24 25 **kwargs
25 ) -> str:
26 ) -> AsyncGenerator:
26 27 if not model:
27 28 model = "gpt-3.5-turbo"
28 29 elif not model in domains:
Modified g4f/Provider/Aibn.py +2 -2
@@ -4,7 +4,7 @@ import time
4 4 import hashlib
5 5
6 6 from ..typing import AsyncGenerator
7 from ..requests import StreamRequest
7 from ..requests import StreamSession
8 8 from .base_provider import AsyncGeneratorProvider
9 9
10 10
@@ -20,7 +20,7 @@ class Aibn(AsyncGeneratorProvider):
20 20 messages: list[dict[str, str]],
21 21 **kwargs
22 22 ) -> AsyncGenerator:
23 async with StreamRequest(impersonate="chrome107") as session:
23 async with StreamSession(impersonate="chrome107") as session:
24 24 timestamp = int(time.time())
25 25 data = {
26 26 "messages": messages,
Modified g4f/Provider/helper.py +5 -1
@@ -21,7 +21,11 @@ def get_event_loop() -> AbstractEventLoop:
21 21 try:
22 22 asyncio.get_running_loop()
23 23 except RuntimeError:
24 return asyncio.get_event_loop()
24 try:
25 return asyncio.get_event_loop()
26 except RuntimeError:
27 asyncio.set_event_loop(asyncio.new_event_loop())
28 return asyncio.get_event_loop()
25 29 try:
26 30 event_loop = asyncio.get_event_loop()
27 31 if not hasattr(event_loop.__class__, "_nest_patched"):
Modified testing/test_async.py +7 -12
@@ -5,31 +5,26 @@ import asyncio
5 5 sys.path.append(str(Path(__file__).parent.parent))
6 6
7 7 import g4f
8 from g4f.Provider import AsyncProvider
9 8 from testing.test_providers import get_providers
10 9 from testing.log_time import log_time_async
11 10
12 11 async def create_async(provider):
13 model = g4f.models.gpt_35_turbo.name if provider.supports_gpt_35_turbo else g4f.models.default.name
14 12 try:
15 13 response = await log_time_async(
16 14 provider.create_async,
17 model=model,
18 messages=[{"role": "user", "content": "Hello Assistant!"}]
15 model=g4f.models.default.name,
16 messages=[{"role": "user", "content": "Hello, are you GPT 3.5?"}]
19 17 )
20 18 print(f"{provider.__name__}:", response)
21 19 except Exception as e:
22 return f"{provider.__name__}: {e.__class__.__name__}: {e}"
20 print(f"{provider.__name__}: {e.__class__.__name__}: {e}")
23 21
24 22 async def run_async():
25 23 responses: list = [
26 create_async(_provider)
27 for _provider in get_providers()
28 if _provider.working and issubclass(_provider, AsyncProvider)
24 create_async(provider)
25 for provider in get_providers()
26 if provider.working
29 27 ]
30 responses = await asyncio.gather(*responses)
31 for error in responses:
32 if error:
33 print(error)
28 await asyncio.gather(*responses)
34 29
35 30 print("Total:", asyncio.run(log_time_async(run_async)))