返回提交历史
Added
g4f/Provider/Perplexity.py
+151
-0
Modified
g4f/Provider/__init__.py
+1
-0
XFEstudio/gpt4free
Add Perplexity provider with REST SSE API support
Co-authored-by: hlohaus <983577+hlohaus@users.noreply.github.com>
fa644e4e
代码差异
2 个文件
+152
-0
@@ -0,0 +1,151 @@
1
from __future__ import annotations
2
3
import json
4
import uuid
5
6
from ..typing import AsyncResult, Messages
7
from ..requests import StreamSession, raise_for_status
8
from ..errors import ResponseError
9
from ..providers.response import FinishReason
10
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
11
12
class Perplexity(AsyncGeneratorProvider, ProviderModelMixin):
13
label = "Perplexity"
14
url = "https://www.perplexity.ai"
15
working = True
16
supports_stream = True
17
supports_system_message = True
18
supports_message_history = True
19
20
default_model = "turbo"
21
models = [
22
default_model,
23
"sonar",
24
"sonar-pro",
25
]
26
27
@classmethod
28
async def create_async_generator(
29
cls,
30
model: str,
31
messages: Messages,
32
proxy: str = None,
33
**kwargs
34
) -> AsyncResult:
35
model = cls.get_model(model)
36
37
# Generate UUIDs for request tracking
38
frontend_uuid = str(uuid.uuid4())
39
frontend_context_uuid = str(uuid.uuid4())
40
visitor_id = str(uuid.uuid4())
41
request_id = str(uuid.uuid4())
42
43
headers = {
44
"accept": "text/event-stream",
45
"accept-language": "en-US,en;q=0.9",
46
"cache-control": "no-cache",
47
"content-type": "application/json",
48
"origin": cls.url,
49
"referer": f"{cls.url}/",
50
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
51
"x-perplexity-request-reason": "perplexity-query-state-provider",
52
"x-request-id": request_id,
53
}
54
55
# Extract the last user message as the query
56
query = ""
57
for message in reversed(messages):
58
if message["role"] == "user":
59
query = message["content"]
60
break
61
62
# Prepare the request payload
63
data = {
64
"params": {
65
"attachments": [],
66
"language": "en-US",
67
"timezone": "America/New_York",
68
"search_focus": "internet",
69
"sources": ["web"],
70
"search_recency_filter": None,
71
"frontend_uuid": frontend_uuid,
72
"mode": "concise",
73
"model_preference": model,
74
"is_related_query": False,
75
"is_sponsored": False,
76
"visitor_id": visitor_id,
77
"frontend_context_uuid": frontend_context_uuid,
78
"prompt_source": "user",
79
"query_source": "home",
80
"is_incognito": False,
81
"time_from_first_type": 0,
82
"local_search_enabled": False,
83
"use_schematized_api": True,
84
"send_back_text_in_streaming_api": False,
85
"supported_block_use_cases": [
86
"answer_modes",
87
"media_items",
88
"knowledge_cards",
89
"inline_entity_cards",
90
"place_widgets",
91
"finance_widgets",
92
"sports_widgets",
93
"shopping_widgets",
94
"jobs_widgets",
95
"search_result_widgets",
96
"clarification_responses",
97
"inline_images",
98
"inline_assets",
99
"inline_finance_widgets",
100
"placeholder_cards",
101
"diff_blocks",
102
"inline_knowledge_cards",
103
"entity_group_v2",
104
"refinement_filters",
105
"canvas_mode"
106
],
107
"client_coordinates": None,
108
"mentions": [],
109
"dsl_query": query,
110
"skip_search_enabled": False,
111
"is_nav_suggestions_disabled": False,
112
"always_search_override": False,
113
"override_no_search": False,
114
"comet_max_assistant_enabled": False,
115
"version": "2.18"
116
},
117
"query_str": query
118
}
119
120
async with StreamSession(headers=headers, proxy=proxy, impersonate="chrome") as session:
121
async with session.post(
122
f"{cls.url}/rest/sse/perplexity_ask",
123
json=data,
124
) as response:
125
await raise_for_status(response)
126
127
# Parse SSE stream
128
async for line in response.content:
129
if line:
130
line = line.decode('utf-8').strip()
131
if line.startswith("data: "):
132
data_str = line[6:]
133
if data_str == "[DONE]":
134
break
135
try:
136
json_data = json.loads(data_str)
137
138
# Handle different response types
139
if "text" in json_data:
140
text = json_data["text"]
141
if text:
142
yield text
143
144
# Check if response is final
145
if json_data.get("final", False):
146
yield FinishReason("stop")
147
break
148
149
except json.JSONDecodeError:
150
# Skip malformed JSON
151
continue
@@ -53,6 +53,7 @@ from .Mintlify import Mintlify
53
53
from .OIVSCodeSer2 import OIVSCodeSer2
54
54
from .OIVSCodeSer0501 import OIVSCodeSer0501
55
55
from .OperaAria import OperaAria
56
from .Perplexity import Perplexity
56
57
from .PerplexityLabs import PerplexityLabs
57
58
from .PollinationsAI import PollinationsAI
58
59
from .PollinationsImage import PollinationsImage