Open History to see the last commit
1import { getPerplexityApiKeyFromEnv } from '../utils/api-key'
2import { getPerplexityIntegrationHeaders } from '../utils/attribution'
3
4export interface PerplexitySearchClientConfig {
5 /** Perplexity API key. Falls back to `PERPLEXITY_API_KEY` / `PPLX_API_KEY` env vars. */
6 apiKey?: string
7 /** Override the API base URL (defaults to https://api.perplexity.ai). */
8 baseURL?: string
9 /** Optional `fetch` implementation; defaults to globalThis.fetch. */
10 fetch?: typeof fetch
11}
12
13export interface PerplexitySearchRequest {
14 /** The search query, or up to 5 queries. */
15 query: string | ReadonlyArray<string>
16 /** Maximum number of results to return (1–20). Defaults to the API default (10). */
17 max_results?: number
18 /** Maximum tokens of content to return per page. */
19 max_tokens_per_page?: number
20 /**
21 * Restrict (or exclude) results by domain (max 20 entries).
22 *
23 * Hostnames, optional paths, or TLDs. Use bare entries to allowlist
24 * (`["nytimes.com"]`) or `-` prefixed entries to denylist
25 * (`["-pinterest.com"]`). Allow and deny entries must NOT be mixed.
26 */
27 search_domain_filter?: Array<string>
28 /** Restrict results by recency: `hour | day | week | month | year`. */
29 search_recency_filter?: 'hour' | 'day' | 'week' | 'month' | 'year'
30 /** Only include results published on or after this date (m/d/yyyy). */
31 search_after_date_filter?: string
32 /** Only include results published on or before this date (m/d/yyyy). */
33 search_before_date_filter?: string
34}
35
36export interface PerplexitySearchResult {
37 title: string
38 url: string
39 snippet: string
40 date?: string
41 last_updated?: string
42}
43
44export interface PerplexitySearchResponse {
45 id?: string
46 results: Array<PerplexitySearchResult>
47}
48
49const DEFAULT_BASE_URL = 'https://api.perplexity.ai'
50const MAX_QUERY_BATCH = 5
51const MAX_DOMAIN_FILTER = 20
52
53/**
54 * Low-level HTTP client for the Perplexity Search API.
55 *
56 * Calls `POST {baseURL}/search` with bearer auth.
57 */
58export class PerplexitySearchClient {
59 private readonly apiKey: string
60 private readonly baseURL: string
61 private readonly fetchImpl: typeof fetch
62
63 constructor(config: PerplexitySearchClientConfig = {}) {
64 const { apiKey } = config
65 const resolvedApiKey =
66 typeof apiKey === 'string' && apiKey.trim().length > 0
67 ? apiKey
68 : getPerplexityApiKeyFromEnv()
69
70 this.apiKey = resolvedApiKey
71 this.baseURL = (config.baseURL ?? DEFAULT_BASE_URL).replace(/\/$/, '')
72 this.fetchImpl = config.fetch ?? globalThis.fetch
73 }
74
75 async search(
76 request: PerplexitySearchRequest,
77 init: { signal?: AbortSignal } = {},
78 ): Promise<PerplexitySearchResponse> {
79 const query = normalizeQuery(request.query)
80 validateDomainFilter(request.search_domain_filter)
81
82 const body: Record<string, unknown> = { query }
83 if (request.max_results !== undefined)
84 body.max_results = requireMaxResults(request.max_results)
85 if (request.max_tokens_per_page !== undefined)
86 body.max_tokens_per_page = request.max_tokens_per_page
87 if (request.search_domain_filter)
88 body.search_domain_filter = request.search_domain_filter
89 if (request.search_recency_filter)
90 body.search_recency_filter = request.search_recency_filter
91 if (request.search_after_date_filter)
92 body.search_after_date_filter = request.search_after_date_filter
93 if (request.search_before_date_filter)
94 body.search_before_date_filter = request.search_before_date_filter
95
96 const response = await this.fetchImpl(`${this.baseURL}/search`, {
97 method: 'POST',
98 headers: {
99 Authorization: `Bearer ${this.apiKey}`,
100 'Content-Type': 'application/json',
101 Accept: 'application/json',
102 ...getPerplexityIntegrationHeaders(),
103 },
104 body: JSON.stringify(body),
105 signal: init.signal,
106 })
107
108 if (!response.ok) {
109 const text = await safeReadText(response)
110 throw new Error(
111 `Perplexity Search API request failed: ${response.status} ${response.statusText}${
112 text ? ` — ${text}` : ''
113 }`,
114 )
115 }
116
117 return parseSearchResponse(await response.json())
118 }
119}
120
121function normalizeQuery(
122 query: string | ReadonlyArray<string>,
123): string | Array<string> {
124 if (typeof query === 'string') {
125 const trimmed = query.trim()
126 if (trimmed.length === 0) {
127 throw new Error(
128 'PerplexitySearchClient.search requires a non-empty `query`.',
129 )
130 }
131 return trimmed
132 }
133
134 if (query.length === 0) {
135 throw new Error(
136 'PerplexitySearchClient.search requires a non-empty `query`.',
137 )
138 }
139 if (query.length > MAX_QUERY_BATCH) {
140 throw new Error(
141 `query array must contain at most ${MAX_QUERY_BATCH} entries.`,
142 )
143 }
144
145 return query.map((entry) => {
146 if (typeof entry !== 'string' || entry.trim().length === 0) {
147 throw new Error(
148 'PerplexitySearchClient.search requires a non-empty `query`.',
149 )
150 }
151 return entry.trim()
152 })
153}
154
155function requireMaxResults(maxResults: number): number {
156 if (!Number.isInteger(maxResults) || maxResults < 1 || maxResults > 20) {
157 throw new Error('max_results must be an integer between 1 and 20.')
158 }
159 return maxResults
160}
161
162function validateDomainFilter(filter: Array<string> | undefined): void {
163 if (!filter || filter.length === 0) return
164 if (filter.length > MAX_DOMAIN_FILTER) {
165 throw new Error(
166 `search_domain_filter must contain at most ${MAX_DOMAIN_FILTER} entries.`,
167 )
168 }
169 let hasAllow = false
170 let hasDeny = false
171 for (const entry of filter) {
172 if (typeof entry !== 'string' || entry.length === 0) continue
173 if (entry.startsWith('-')) hasDeny = true
174 else hasAllow = true
175 }
176 if (hasAllow && hasDeny) {
177 throw new Error(
178 'search_domain_filter cannot mix allowlist and denylist entries. Use only `-domain.com` for negation, or only bare domains for allowlist.',
179 )
180 }
181}
182
183function isSearchResult(value: unknown): value is PerplexitySearchResult {
184 if (typeof value !== 'object' || value === null) return false
185 const result = value as {
186 title?: unknown
187 url?: unknown
188 snippet?: unknown
189 date?: unknown
190 last_updated?: unknown
191 }
192 return (
193 typeof result.title === 'string' &&
194 typeof result.url === 'string' &&
195 typeof result.snippet === 'string' &&
196 (result.date === undefined ||
197 result.date === null ||
198 typeof result.date === 'string') &&
199 (result.last_updated === undefined ||
200 result.last_updated === null ||
201 typeof result.last_updated === 'string')
202 )
203}
204
205function parseSearchResponse(value: unknown): PerplexitySearchResponse {
206 if (typeof value !== 'object' || value === null) {
207 throw new Error('Perplexity Search API returned an invalid response.')
208 }
209 const data = value as { id?: unknown; results?: unknown }
210 if (!Array.isArray(data.results) || !data.results.every(isSearchResult)) {
211 throw new Error('Perplexity Search API returned an invalid response.')
212 }
213 return {
214 ...(typeof data.id === 'string' ? { id: data.id } : {}),
215 results: data.results.map((result) => ({
216 title: result.title,
217 url: result.url,
218 snippet: result.snippet,
219 ...(result.date ? { date: result.date } : {}),
220 ...(result.last_updated ? { last_updated: result.last_updated } : {}),
221 })),
222 }
223}
224
225async function safeReadText(response: Response): Promise<string> {
226 try {
227 return await response.text()
228 } catch {
229 return ''
230 }
231}