Open History to see the last commit
1/**
2 * Resolve a Perplexity API key from environment variables.
3 *
4 * Honors `PERPLEXITY_API_KEY` first, then falls back to `PPLX_API_KEY`.
5 * Throws if neither is set.
6 */
7export function getPerplexityApiKeyFromEnv(): string {
8 const env = getEnvironment()
9 const key = [env?.PERPLEXITY_API_KEY, env?.PPLX_API_KEY]
10 .find(
11 (value): value is string =>
12 typeof value === 'string' && value.trim().length > 0,
13 )
14 ?.trim()
15
16 if (!key) {
17 throw new Error(
18 'PERPLEXITY_API_KEY (or PPLX_API_KEY) is required. Set it in your environment or pass an explicit apiKey.',
19 )
20 }
21
22 return key
23}
24
25interface WindowWithEnv {
26 env?: Record<string, string | undefined>
27}
28
29function getEnvironment(): Record<string, string | undefined> | undefined {
30 if (typeof globalThis !== 'undefined') {
31 const win = (globalThis as { window?: WindowWithEnv }).window
32 if (win?.env) return win.env
33 }
34 if (typeof process !== 'undefined') {
35 return process.env
36 }
37 return undefined
38}