返回提交历史
Added
g4f/Provider/needs_auth/Perplexity.py
+179
-0
Modified
g4f/Provider/needs_auth/__init__.py
+1
-0
XFEstudio/gpt4free
Implement basic Perplexity cookie-based provider structure
Co-authored-by: hlohaus <983577+hlohaus@users.noreply.github.com>
d18d8e9b
代码差异
2 个文件
+180
-0
@@ -0,0 +1,179 @@
1
from __future__ import annotations
2
3
import json
4
import uuid
5
import random
6
import time
7
import re
8
from typing import Dict, List
9
10
from aiohttp import ClientSession, BaseConnector
11
12
from ...typing import AsyncResult, Messages, Cookies
13
from ...requests import raise_for_status, DEFAULT_HEADERS, StreamSession
14
from ...errors import ResponseError, MissingAuthError
15
from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
16
from ..helper import format_prompt, get_connector, format_cookies
17
18
class Perplexity(AsyncGeneratorProvider, ProviderModelMixin):
19
label = "Perplexity"
20
url = "https://www.perplexity.ai"
21
working = True
22
needs_auth = True
23
default_model = "claude-3.5-sonnet"
24
25
# Models available with Pro subscription via web interface
26
models = [
27
"claude-3.5-sonnet",
28
"claude-3.5-haiku",
29
"gpt-4o",
30
"gpt-4o-mini",
31
"gemini-2.0-flash-experimental",
32
"o1-preview",
33
"o1-mini",
34
"llama-3.1-sonar-large-128k-online",
35
"llama-3.1-sonar-large-128k-chat",
36
"llama-3.1-sonar-huge-128k-online"
37
]
38
39
@classmethod
40
async def create_async_generator(
41
cls,
42
model: str,
43
messages: Messages,
44
proxy: str = None,
45
cookies: Cookies = None,
46
**kwargs
47
) -> AsyncResult:
48
if cookies is None:
49
raise MissingAuthError("Cookies are required for Perplexity authentication. Please provide cookies from a logged-in Perplexity session.")
50
51
headers = {
52
'accept': '*/*',
53
'accept-encoding': 'gzip, deflate, br, zstd',
54
'accept-language': 'en-US,en;q=0.9',
55
'content-type': 'application/json',
56
'origin': cls.url,
57
'referer': f'{cls.url}/',
58
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
59
}
60
61
async with StreamSession(headers=headers, proxy=proxy, cookies=cookies, impersonate="chrome") as session:
62
# First, get the main page to extract any necessary tokens or session info
63
async with session.get(cls.url) as response:
64
await raise_for_status(response, "Failed to load Perplexity homepage")
65
page_content = await response.text()
66
67
# Extract necessary tokens/session info from the page
68
# This is a common pattern for web-based chat interfaces
69
csrf_token = None
70
session_id = None
71
72
# Look for common token patterns in the page HTML
73
csrf_match = re.search(r'"csrf[_-]?token["\']\s*:\s*["\']([^"\']+)', page_content, re.IGNORECASE)
74
if csrf_match:
75
csrf_token = csrf_match.group(1)
76
77
session_match = re.search(r'"session[_-]?id["\']\s*:\s*["\']([^"\']+)', page_content, re.IGNORECASE)
78
if session_match:
79
session_id = session_match.group(1)
80
81
# Try common chat API endpoints
82
chat_endpoints = [
83
f"{cls.url}/api/chat",
84
f"{cls.url}/api/copilot/chat",
85
f"{cls.url}/api/ask",
86
f"{cls.url}/api/query"
87
]
88
89
# Format the message for the API
90
formatted_messages = []
91
for msg in messages:
92
if isinstance(msg.get("content"), str):
93
formatted_messages.append({
94
"role": msg["role"],
95
"content": msg["content"]
96
})
97
98
# Prepare the request payload
99
payload = {
100
"messages": formatted_messages,
101
"model": model,
102
"stream": True
103
}
104
105
# Add tokens if found
106
if csrf_token:
107
headers['x-csrf-token'] = csrf_token
108
if session_id:
109
headers['x-session-id'] = session_id
110
111
# Try each endpoint until we find one that works
112
last_error = None
113
114
for endpoint in chat_endpoints:
115
try:
116
async with session.post(endpoint, json=payload, headers=headers) as response:
117
if response.status == 200:
118
# Handle streaming response
119
buffer = ""
120
async for line in response.content:
121
if not line:
122
continue
123
124
line_text = line.decode('utf-8').strip()
125
if not line_text:
126
continue
127
128
buffer += line_text
129
130
# Handle different streaming formats
131
if line_text.startswith("data: "):
132
data_str = line_text[6:]
133
if data_str == "[DONE]":
134
break
135
try:
136
data = json.loads(data_str)
137
if "choices" in data and data["choices"]:
138
delta = data["choices"][0].get("delta", {})
139
if "content" in delta:
140
yield delta["content"]
141
elif "message" in data:
142
yield data["message"]
143
elif "text" in data:
144
yield data["text"]
145
elif isinstance(data, str):
146
yield data
147
except json.JSONDecodeError:
148
# If it's not JSON, yield the raw text
149
yield data_str
150
elif line_text.startswith("{"):
151
# Handle JSON responses
152
try:
153
data = json.loads(line_text)
154
if "choices" in data and data["choices"]:
155
delta = data["choices"][0].get("delta", {})
156
if "content" in delta:
157
yield delta["content"]
158
except json.JSONDecodeError:
159
pass
160
else:
161
# Handle plain text responses
162
yield line_text
163
return
164
else:
165
last_error = f"HTTP {response.status}: {await response.text()}"
166
continue
167
168
except Exception as e:
169
last_error = str(e)
170
continue
171
172
# If we get here, none of the endpoints worked
173
# Provide a helpful error message and basic functionality
174
error_msg = f"Unable to connect to Perplexity chat API. Last error: {last_error}"
175
yield f"Error: {error_msg}\n\n"
176
yield "This provider requires cookies from a logged-in Perplexity.ai session. "
177
yield "Please ensure you're using valid authentication cookies from your browser.\n\n"
178
yield f"Your query was: {format_prompt(messages)}\n"
179
yield f"Selected model: {model}\n"
@@ -30,6 +30,7 @@ from .OpenaiAPI import OpenaiAPI
30
30
from .OpenaiChat import OpenaiChat
31
31
from .OpenRouter import OpenRouter
32
32
from .OpenRouter import OpenRouterFree
33
from .Perplexity import Perplexity
33
34
from .PerplexityApi import PerplexityApi
34
35
from .Pi import Pi
35
36
from .PuterJS import PuterJS