Open History to see the last commit
1import * as fs from "fs";
2import * as path from "path";
3import chalk from "chalk";
4import type { AIAdapter } from "@tanstack/ai";
5
6export const API_KEY_URLS = {
7 openai: "https://platform.openai.com/api-keys",
8 anthropic: "https://console.anthropic.com/settings/keys",
9 gemini: "https://aistudio.google.com/app/apikey",
10 ollama: "https://ollama.ai/download",
11};
12
13export function getApiKeyUrl(provider: string): string {
14 const key = provider.toLowerCase();
15 return API_KEY_URLS[key as keyof typeof API_KEY_URLS] || "";
16}
17
18export async function saveApiKeyToEnv(
19 envVarName: string,
20 apiKey: string
21): Promise<boolean> {
22 try {
23 const envPath = path.join(process.cwd(), ".env");
24 let envContent = "";
25
26 // Read existing .env file if it exists
27 if (fs.existsSync(envPath)) {
28 envContent = fs.readFileSync(envPath, "utf-8");
29 }
30
31 // Check if the key already exists
32 const regex = new RegExp(`^${envVarName}=.*$`, "m");
33 if (regex.test(envContent)) {
34 // Update existing key
35 envContent = envContent.replace(regex, `${envVarName}=${apiKey}`);
36 } else {
37 // Add new key
38 if (envContent && !envContent.endsWith("\n")) {
39 envContent += "\n";
40 }
41 envContent += `${envVarName}=${apiKey}\n`;
42 }
43
44 // Write the updated content
45 fs.writeFileSync(envPath, envContent);
46 console.log(chalk.green(`✅ API key saved to .env file`));
47 return true;
48 } catch (error) {
49 console.error(chalk.red(`Failed to save API key: ${error}`));
50 return false;
51 }
52}
53
54export function maskApiKey(apiKey: string): string {
55 if (!apiKey || apiKey.length < 8) return "***";
56 return `${apiKey.slice(0, 4)}...${apiKey.slice(-4)}`;
57}
58
59export async function validateApiKey(
60 adapter: AIAdapter,
61 provider: string
62): Promise<boolean> {
63 try {
64 // Make a minimal test request to validate the key
65 const testMessages = [{ role: "user" as const, content: "Hi" }];
66
67 switch (provider.toLowerCase()) {
68 case "openai":
69 case "anthropic":
70 case "gemini":
71 await adapter.chatCompletion({
72 model:
73 provider === "gemini"
74 ? "gemini-pro"
75 : provider === "anthropic"
76 ? "claude-3-haiku-20240307"
77 : "gpt-3.5-turbo",
78 messages: testMessages,
79 maxTokens: 1,
80 });
81 return true;
82 case "ollama":
83 // For Ollama, just check if we can list models
84 try {
85 await adapter.chatCompletion({
86 model: "llama2",
87 messages: testMessages,
88 maxTokens: 1,
89 });
90 } catch (error: any) {
91 // If the error is about the model not being found, the connection is OK
92 if (
93 error.message?.includes("model") ||
94 error.message?.includes("not found")
95 ) {
96 return true;
97 }
98 throw error;
99 }
100 return true;
101 default:
102 return false;
103 }
104 } catch (error: any) {
105 // Check for specific authentication errors
106 if (
107 error.message?.includes("401") ||
108 error.message?.includes("403") ||
109 error.message?.includes("API key") ||
110 error.message?.includes("authentication") ||
111 error.message?.includes("Invalid") ||
112 error.message?.includes("Incorrect")
113 ) {
114 return false;
115 }
116 // Other errors might be network issues, not auth issues
117 throw error;
118 }
119}