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

XFEstudio/gpt4free

Fix create_event_loop function Add PerplexityAi Provider

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

代码差异

3 个文件 +100 -10
Added g4f/Provider/PerplexityAi.py +87 -0
@@ -0,0 +1,87 @@
1 from __future__ import annotations
2
3 import json
4 import time
5 import base64
6 from curl_cffi.requests import AsyncSession
7
8 from .base_provider import AsyncProvider, format_prompt
9
10
11 class PerplexityAi(AsyncProvider):
12 url = "https://www.perplexity.ai"
13 working = True
14 supports_gpt_35_turbo = True
15 _sources = []
16
17 @classmethod
18 async def create_async(
19 cls,
20 model: str,
21 messages: list[dict[str, str]],
22 proxy: str = None,
23 **kwargs
24 ) -> str:
25 url = cls.url + "/socket.io/?EIO=4&transport=polling"
26 async with AsyncSession(proxies={"https": proxy}, impersonate="chrome107") as session:
27 url_session = "https://www.perplexity.ai/api/auth/session"
28 response = await session.get(url_session)
29
30 response = await session.get(url, params={"t": timestamp()})
31 response.raise_for_status()
32 sid = json.loads(response.text[1:])["sid"]
33
34 data = '40{"jwt":"anonymous-ask-user"}'
35 response = await session.post(url, params={"t": timestamp(), "sid": sid}, data=data)
36 response.raise_for_status()
37
38 data = "424" + json.dumps([
39 "perplexity_ask",
40 format_prompt(messages),
41 {
42 "version":"2.1",
43 "source":"default",
44 "language":"en",
45 "timezone": time.tzname[0],
46 "search_focus":"internet",
47 "mode":"concise"
48 }
49 ])
50 response = await session.post(url, params={"t": timestamp(), "sid": sid}, data=data)
51 response.raise_for_status()
52
53 while True:
54 response = await session.get(url, params={"t": timestamp(), "sid": sid})
55 response.raise_for_status()
56 for line in response.text.splitlines():
57 if line.startswith("434"):
58 result = json.loads(json.loads(line[3:])[0]["text"])
59
60 cls._sources = [{
61 "name": source["name"],
62 "url": source["url"],
63 "snippet": source["snippet"]
64 } for source in result["web_results"]]
65
66 return result["answer"]
67
68 @classmethod
69 def get_sources(cls):
70 return cls._sources
71
72
73 @classmethod
74 @property
75 def params(cls):
76 params = [
77 ("model", "str"),
78 ("messages", "list[dict[str, str]]"),
79 ("stream", "bool"),
80 ("proxy", "str"),
81 ]
82 param = ", ".join([": ".join(p) for p in params])
83 return f"g4f.provider.{cls.__name__} supports: ({param})"
84
85
86 def timestamp() -> str:
87 return base64.urlsafe_b64encode(int(time.time()-1407782612).to_bytes(4, 'big')).decode()
Modified g4f/Provider/__init__.py +2 -0
@@ -24,6 +24,7 @@ from .Lockchat import Lockchat
24 24 from .Opchatgpts import Opchatgpts
25 25 from .OpenaiChat import OpenaiChat
26 26 from .OpenAssistant import OpenAssistant
27 from .PerplexityAi import PerplexityAi
27 28 from .Raycast import Raycast
28 29 from .Theb import Theb
29 30 from .Vercel import Vercel
@@ -67,6 +68,7 @@ __all__ = [
67 68 'Raycast',
68 69 'OpenaiChat',
69 70 'OpenAssistant',
71 'PerplexityAi',
70 72 'Theb',
71 73 'Vercel',
72 74 'Vitalentum',
Modified g4f/Provider/base_provider.py +11 -10
@@ -6,7 +6,7 @@ from abc import ABC, abstractmethod
6 6
7 7 import browser_cookie3
8 8
9 from ..typing import Any, AsyncGenerator, CreateResult, Union
9 from ..typing import Any, AsyncGenerator, CreateResult
10 10
11 11
12 12 class BaseProvider(ABC):
@@ -22,7 +22,9 @@ class BaseProvider(ABC):
22 22 def create_completion(
23 23 model: str,
24 24 messages: list[dict[str, str]],
25 stream: bool, **kwargs: Any) -> CreateResult:
25 stream: bool,
26 **kwargs
27 ) -> CreateResult:
26 28
27 29 raise NotImplementedError()
28 30
@@ -118,16 +120,15 @@ class AsyncGeneratorProvider(AsyncProvider):
118 120 raise NotImplementedError()
119 121
120 122
123 # Don't create a new event loop in a running async loop.
124 # Force use selector event loop on windows and linux use it anyway.
121 125 def create_event_loop() -> SelectorEventLoop:
122 # Don't create a new loop in a running loop
123 126 try:
124 if asyncio.get_running_loop() is not None:
125 raise RuntimeError(
126 'Use "create_async" instead of "create" function in a async loop.')
127 except:
128 pass
129 # Force use selector event loop on windows and linux use it anyway
130 return SelectorEventLoop()
127 asyncio.get_running_loop()
128 except RuntimeError:
129 return SelectorEventLoop()
130 raise RuntimeError(
131 'Use "create_async" instead of "create" function in a async loop.')
131 132
132 133
133 134 _cookies = {}