forked from nicobailon/pi-web-access
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperplexity.ts
More file actions
215 lines (183 loc) · 6.47 KB
/
Copy pathperplexity.ts
File metadata and controls
215 lines (183 loc) · 6.47 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
import { existsSync, readFileSync } from "node:fs";
import { activityMonitor } from "./activity.ts";
import type { ExtractedContent } from "./extract.ts";
import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
import { getWebSearchConfigPath } from "./utils.ts";
const PERPLEXITY_API_URL = "https://api.perplexity.ai/chat/completions";
const CONFIG_PATH = getWebSearchConfigPath();
const RATE_LIMIT = {
maxRequests: 10,
windowMs: 60 * 1000,
};
const requestTimestamps: number[] = [];
export interface SearchResult {
title: string;
url: string;
snippet: string;
}
export interface SearchResponse {
answer: string;
results: SearchResult[];
inlineContent?: ExtractedContent[];
}
export interface SearchOptions {
numResults?: number;
recencyFilter?: "day" | "week" | "month" | "year";
domainFilter?: string[];
signal?: AbortSignal;
}
interface WebSearchConfig {
perplexityApiKey?: unknown;
}
let cachedConfig: WebSearchConfig | null = null;
function loadConfig(): WebSearchConfig {
if (cachedConfig) return cachedConfig;
if (!existsSync(CONFIG_PATH)) {
cachedConfig = {};
return cachedConfig;
}
const content = readFileSync(CONFIG_PATH, "utf-8");
try {
cachedConfig = JSON.parse(content) as WebSearchConfig;
return cachedConfig;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
}
}
async function getApiKey(signal?: AbortSignal): Promise<string> {
const key = await resolveCredential({
provider: "Perplexity",
configuredValue: loadConfig().perplexityApiKey,
environmentValue: process.env.PERPLEXITY_API_KEY,
signal,
});
if (!key) {
throw new Error(
"Perplexity API key not found. Either:\n" +
` 1. Create ${CONFIG_PATH} with { "perplexityApiKey": "your-key" }\n` +
" 2. Set PERPLEXITY_API_KEY environment variable\n" +
"Get a key at https://perplexity.ai/settings/api"
);
}
return key;
}
function checkRateLimit(): void {
const now = Date.now();
const windowStart = now - RATE_LIMIT.windowMs;
while (requestTimestamps.length > 0 && requestTimestamps[0] < windowStart) {
requestTimestamps.shift();
}
if (requestTimestamps.length >= RATE_LIMIT.maxRequests) {
const waitMs = requestTimestamps[0] + RATE_LIMIT.windowMs - now;
throw new Error(`Rate limited. Try again in ${Math.ceil(waitMs / 1000)}s`);
}
requestTimestamps.push(now);
}
function validateDomainFilter(domains: string[]): string[] {
return domains.filter((d) => {
const domain = d.startsWith("-") ? d.slice(1) : d;
return /^[a-zA-Z0-9][a-zA-Z0-9-_.]*\.[a-zA-Z]{2,}$/.test(domain);
});
}
export function isPerplexityAvailable(): boolean {
return hasCredentialSource({
provider: "Perplexity",
configuredValue: loadConfig().perplexityApiKey,
environmentValue: process.env.PERPLEXITY_API_KEY,
});
}
/** Hard ceiling on kept citations, matching the `numResults` clamp. */
const MAX_CITATIONS = 20;
// Preserve citation numbering by keeping the prefix through the highest cited index, capped at 20.
function citationsToKeep(answer: string, available: number, numResults: number): number {
let highestCited = 0;
for (const match of answer.matchAll(/\[(\d{1,3})\]/g)) {
highestCited = Math.max(highestCited, Number(match[1]));
}
return Math.min(available, MAX_CITATIONS, Math.max(numResults, highestCited));
}
export async function searchWithPerplexity(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
checkRateLimit();
const activityId = activityMonitor.logStart({ type: "api", query });
activityMonitor.updateRateLimit({
used: requestTimestamps.length,
max: RATE_LIMIT.maxRequests,
oldestTimestamp: requestTimestamps[0] ?? null,
windowMs: RATE_LIMIT.windowMs,
});
const apiKey = await getApiKey(options.signal);
const numResults = typeof options.numResults === "number" && Number.isFinite(options.numResults)
? Math.max(1, Math.min(Math.floor(options.numResults), 20))
: 5;
const requestBody: Record<string, unknown> = {
model: "sonar",
messages: [{ role: "user", content: query }],
max_tokens: 1024,
return_related_questions: false,
};
if (options.recencyFilter) {
requestBody.search_recency_filter = options.recencyFilter;
}
if (options.domainFilter && options.domainFilter.length > 0) {
const validated = validateDomainFilter(options.domainFilter);
if (validated.length > 0) {
requestBody.search_domain_filter = validated;
}
}
let response: Response;
try {
response = await fetch(PERPLEXITY_API_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
...(options.signal ? { signal: options.signal } : {}),
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
const redactedMessage = redactCredential(message, apiKey);
if (redactedMessage.toLowerCase().includes("abort")) {
activityMonitor.logComplete(activityId, 0);
} else {
activityMonitor.logError(activityId, redactedMessage);
}
if (redactedMessage === message) throw err;
const redactedError = new Error(redactedMessage);
if (err instanceof Error) redactedError.name = err.name;
throw redactedError;
}
if (!response.ok) {
activityMonitor.logComplete(activityId, response.status);
const errorText = redactCredential(await response.text(), apiKey);
throw new Error(`Perplexity API error ${response.status}: ${errorText}`);
}
let data: Record<string, unknown>;
try {
data = await response.json();
} catch (err) {
activityMonitor.logComplete(activityId, response.status);
const message = err instanceof Error ? err.message : String(err);
throw new Error(`Perplexity API returned invalid JSON: ${message}`);
}
const answer = (data.choices as Array<{ message?: { content?: string } }>)?.[0]?.message?.content || "";
const citations = Array.isArray(data.citations) ? data.citations : [];
const results: SearchResult[] = [];
const citationCount = citationsToKeep(answer, citations.length, numResults);
for (let i = 0; i < citationCount; i++) {
const citation = citations[i];
if (typeof citation === "string") {
results.push({ title: `Source ${i + 1}`, url: citation, snippet: "" });
} else if (citation && typeof citation === "object" && typeof citation.url === "string") {
results.push({
title: citation.title || `Source ${i + 1}`,
url: citation.url,
snippet: "",
});
}
}
activityMonitor.logComplete(activityId, response.status);
return { answer, results };
}