File size: 1,898 Bytes
f453a26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { auth } from "../config/firebase.js";
import { getBackendUrl } from "./backend_url.js";

export { getBackendUrl };

export function getLlmApiKey(): string {
  return localStorage.getItem("GEO_STRAT_LLM_API_KEY") || "";
}

export function getUnslothApiKey(): string {
  return localStorage.getItem("GEO_STRAT_UNSLOTH_KEY") || "";
}

export function getHfToken(): string {
  return localStorage.getItem("GEO_STRAT_HF_TOKEN") || "";
}

export function getGNewsApiKey(): string {
  return localStorage.getItem("GEO_STRAT_GNEWS_KEY") || "";
}

export function getLlmProvider(): string {
  return localStorage.getItem("GEO_STRAT_LLM_PROVIDER") || "cascade_auto"; // 'cascade_auto', 'gemini', 'unsloth', 'hf_token', 'hf_free'
}

export async function fetchWithAuth(endpoint: string, options: RequestInit = {}): Promise<Response> {
  const baseUrl = getBackendUrl();
  const url = endpoint.startsWith("http") ? endpoint : `${baseUrl}${endpoint}`;

  const headers = new Headers(options.headers || {});
  headers.set("Content-Type", "application/json");

  // Attach LLM Keys & Provider
  const customKey = getLlmApiKey();
  const unslothKey = getUnslothApiKey();
  const hfToken = getHfToken();
  const gnewsKey = getGNewsApiKey();
  const provider = getLlmProvider();

  if (customKey) {
    headers.set("X-LLM-API-Key", customKey);
  }
  if (unslothKey) {
    headers.set("X-Unsloth-Key", unslothKey);
  }
  if (hfToken) {
    headers.set("X-HF-Token", hfToken);
  }
  if (gnewsKey) {
    headers.set("X-GNews-Key", gnewsKey);
  }
  headers.set("X-LLM-Provider", provider);

  // Attach Firebase Auth Token if signed in
  if (auth.currentUser) {
    try {
      const idToken = await auth.currentUser.getIdToken();
      headers.set("Authorization", `Bearer ${idToken}`);
    } catch (_e) {
      // Ignore token fetch error
    }
  }

  return fetch(url, {
    ...options,
    headers,
  });
}