-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerplexity.php
More file actions
230 lines (197 loc) · 5.79 KB
/
Perplexity.php
File metadata and controls
230 lines (197 loc) · 5.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
<?php
namespace Utopia\Agents\Adapters;
use Utopia\Fetch\Chunk;
class Perplexity extends OpenAI
{
/**
* Default Perplexity API endpoint
*/
protected const ENDPOINT = 'https://api.perplexity.ai/chat/completions';
/**
* Sonar - Lightweight, cost-effective search model
*/
public const MODEL_SONAR = 'sonar';
/**
* Sonar Pro - Enhanced search model with advanced features
*/
public const MODEL_SONAR_PRO = 'sonar-pro';
/**
* Sonar Deep Research - Advanced search model with deep analysis capabilities
*/
public const MODEL_SONAR_DEEP_RESEARCH = 'sonar-deep-research';
/**
* Sonar Reasoning - Reasoning model with analysis capabilities
*/
public const MODEL_SONAR_REASONING = 'sonar-reasoning';
/**
* Sonar Reasoning Pro - Enhanced reasoning model with advanced features
*/
public const MODEL_SONAR_REASONING_PRO = 'sonar-reasoning-pro';
/**
* Create a new Perplexity adapter
*
* @param string $apiKey
* @param string $model
* @param int $maxTokens
* @param float $temperature
* @param string|null $endpoint
* @param int $timeout
*
* @throws \Exception
*/
public function __construct(
string $apiKey,
string $model = self::MODEL_SONAR,
int $maxTokens = 1024,
float $temperature = 1.0,
?string $endpoint = null,
int $timeout = 90
) {
parent::__construct(
$apiKey,
$model,
$maxTokens,
$temperature,
$endpoint ?? self::ENDPOINT,
$timeout
);
}
/**
* Check if the model supports JSON schema
*
* @return bool
*/
public function isSchemaSupported(): bool
{
return true;
}
/**
* Get available models
*
* @return array<string>
*/
public function getModels(): array
{
return [
self::MODEL_SONAR,
self::MODEL_SONAR_PRO,
self::MODEL_SONAR_DEEP_RESEARCH,
self::MODEL_SONAR_REASONING,
self::MODEL_SONAR_REASONING_PRO,
];
}
/**
* Get the adapter name
*
* @return string
*/
public function getName(): string
{
return 'perplexity';
}
/**
* Get support for embeddings
*
* @return bool
*/
public function getSupportForEmbeddings(): bool
{
return false;
}
/**
* Process a stream chunk from the Perplexity API
*
* @param \Utopia\Fetch\Chunk $chunk
* @param callable|null $listener
* @return string
*
* @throws \Exception
*/
protected function process(Chunk $chunk, ?callable $listener): string
{
$block = '';
$data = $chunk->getData();
$lines = explode("\n", $data);
$json = json_decode($data, true);
if (is_array($json) && isset($json['error'])) {
return $this->formatErrorMessage($json);
}
// Specifically for Authorization and similar errors that return HTML
$trimmed = ltrim($data);
if (
stripos($trimmed, '<html') === 0 ||
stripos($trimmed, '<!DOCTYPE html') === 0
) {
return $this->sanitizeHtmlError($data);
}
foreach ($lines as $line) {
if (empty(trim($line))) {
continue;
}
if (! str_starts_with($line, 'data: ')) {
continue;
}
// Handle [DONE] message
if (trim($line) === 'data: [DONE]') {
continue;
}
$json = json_decode(substr($line, 6), true);
if (! is_array($json)) {
continue;
}
// Extract content from the choices array
if (isset($json['choices'][0]['delta']['content'])) {
$block = $json['choices'][0]['delta']['content'];
if (! empty($block) && $listener !== null) {
$listener($block);
}
}
}
return $block;
}
/**
* Sanitize HTML error responses into readable error messages
*
* @param string $html
* @return string
*/
protected function sanitizeHtmlError(string $html): string
{
// Try to extract the error from the title tag
if (preg_match('/<title>(.*?)<\/title>/is', $html, $matches)) {
$errorMessage = trim($matches[1]);
// Extract status code and message if present (e.g., "401 Authorization Required")
if (preg_match('/^(\d{3})\s+(.+)$/i', $errorMessage, $parts)) {
$statusCode = $parts[1];
$message = $parts[2];
return '(http_'.$statusCode.') '.$message;
}
return '(html_error) '.$errorMessage;
}
// Try to extract from h1 tag
if (preg_match('/<h1>(.*?)<\/h1>/is', $html, $matches)) {
$errorMessage = trim(strip_tags($matches[1]));
if (preg_match('/^(\d{3})\s+(.+)$/i', $errorMessage, $parts)) {
$statusCode = $parts[1];
$message = $parts[2];
return '(http_'.$statusCode.') '.$message;
}
return '(html_error) '.$errorMessage;
}
// Fallback for unrecognized HTML errors
return '(html_error) Received HTML error response from API';
}
/**
* @param string $text
* @return array{
* embedding: array<int, float>,
* tokensProcessed: int|null,
* totalDuration: int|null ,
* modelLoadingDuration: int|null
* }
*/
public function embed(string $text): array
{
throw new \Exception('Embeddings are not supported for this adapter.');
}
}