返回提交历史
Modified
g4f/Provider/Perplexity.py
+35
-8
XFEstudio/gpt4free
Improve Perplexity provider with better response handling and Sources support
Co-authored-by: hlohaus <983577+hlohaus@users.noreply.github.com>
6b917f68
代码差异
1 个文件
+35
-8
@@ -6,7 +6,7 @@ import uuid
6
6
from ..typing import AsyncResult, Messages
7
7
from ..requests import StreamSession, raise_for_status
8
8
from ..errors import ResponseError
9
from ..providers.response import FinishReason
9
from ..providers.response import FinishReason, Sources
10
10
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
11
11
12
12
class Perplexity(AsyncGeneratorProvider, ProviderModelMixin):
@@ -124,6 +124,9 @@ class Perplexity(AsyncGeneratorProvider, ProviderModelMixin):
124
124
) as response:
125
125
await raise_for_status(response)
126
126
127
# Track last message position for incremental updates
128
last_message = 0
129
127
130
# Parse SSE stream
128
131
async for line in response.content:
129
132
if line:
@@ -135,17 +138,41 @@ class Perplexity(AsyncGeneratorProvider, ProviderModelMixin):
135
138
try:
136
139
json_data = json.loads(data_str)
137
140
138
# Handle different response types
139
if "text" in json_data:
141
# Handle error responses
142
if json_data.get("status") == "failed":
143
error_message = json_data.get("text", "Unknown API error")
144
raise ResponseError(f"API Error: {error_message}")
145
146
# Handle normal responses with 'output' field (like PerplexityLabs)
147
if "output" in json_data:
148
# Yield incremental output
149
output = json_data["output"]
150
if len(output) > last_message:
151
yield output[last_message:]
152
last_message = len(output)
153
154
# Check if response is final
155
if json_data.get("final", False):
156
# Yield citations if available
157
if json_data.get("citations"):
158
yield Sources(json_data["citations"])
159
yield FinishReason("stop")
160
break
161
162
# Handle alternative response format with 'text' field
163
elif "text" in json_data:
140
164
text = json_data["text"]
141
165
if text:
142
166
yield text
143
144
# Check if response is final
145
if json_data.get("final", False):
146
yield FinishReason("stop")
147
break
167
168
# Check if response is final
169
if json_data.get("final", False):
170
yield FinishReason("stop")
171
break
148
172
149
173
except json.JSONDecodeError:
150
174
# Skip malformed JSON
151
175
continue
176
except ResponseError:
177
# Re-raise ResponseError directly
178
raise