Repository navigation
Expand file tree
/
Copy pathimplementation.js
More file actions
83 lines (78 loc) · 2.33 KB
/
Copy pathimplementation.js
File metadata and controls
83 lines (78 loc) · 2.33 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
const LEGACY_MODELS = {
sonar: 'perplexity/sonar',
'sonar-pro': 'perplexity/sonar',
'sonar-reasoning': 'perplexity/sonar',
'sonar-reasoning-pro': 'perplexity/sonar',
'sonar-deep-research': 'perplexity/sonar',
};
function search_via_perplexity(params, userSettings) {
const keyword = params.keyword;
const model =
LEGACY_MODELS[userSettings.model] ||
userSettings.model ||
'perplexity/sonar';
const systemMessage = userSettings.systemMessage || 'Be precise and concise.';
const key = userSettings.apiKey;
const maxResults = Math.min(
50,
Math.max(1, parseInt(userSettings.maxResults) || 10),
);
if (!key) {
throw new Error(
'Please set the Perplexity API Key in the plugin settings.',
);
}
return fetch('https://api.perplexity.ai/v1/responses', {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json',
authorization: 'Bearer ' + key,
},
body: JSON.stringify({
model: model,
instructions: systemMessage,
input: keyword,
tools: [{ type: 'web_search', max_results: maxResults }],
tool_choice: { type: 'web_search' },
}),
})
.then((res) => {
if (!res.ok) {
return res.text().then((err) => {
throw new Error(
`Perplexity API error (${res.status}). Details: ${err}`,
);
});
}
return res.json();
})
.then((response) => {
if (response.status === 'failed' || response.status === 'cancelled') {
const details =
response.error?.message ||
JSON.stringify(response.error) ||
response.status;
throw new Error(`Perplexity API error. Details: ${details}`);
}
const output = response.output || [];
const content = output
.filter((o) => o.type === 'message')
.flatMap((o) => o.content || [])
.filter((c) => c.type === 'output_text')
.map((c) => c.text || '')
.join('');
const citations = output
.filter((o) => o.type === 'search_results')
.flatMap((o) => o.results || [])
.map((r) => r.url)
.filter(Boolean);
return (
content +
(citations.length
? '\n\n Citations:\n' +
citations.map((c, index) => `[${index + 1}] ${c}`).join('\n')
: '')
);
});
}