mirror of https://github.com/kortix-ai/suna.git
frontend for local api key management
This commit is contained in:
parent
81d23215dd
commit
44906ee3d0
|
@ -22,7 +22,6 @@ def save_local_llm_keys(request: Dict[str, str]) -> Dict[str, str]:
|
|||
if config.ENV_MODE != EnvMode.LOCAL:
|
||||
raise HTTPException(status_code=403, detail="API key management only available in local mode")
|
||||
|
||||
print(f"Saving local LLM keys: {request}")
|
||||
key_saved = save_local_api_keys(request)
|
||||
if key_saved:
|
||||
return {"message": "API keys saved successfully"}
|
||||
|
|
|
@ -14,12 +14,9 @@ from utils.constants import PROVIDERS
|
|||
|
||||
def get_local_api_keys(providers: List[str]) -> Dict[str, str]:
|
||||
"""Get API keys from .env file in local mode."""
|
||||
if config.ENV_MODE != EnvMode.LOCAL:
|
||||
return {}
|
||||
|
||||
try:
|
||||
# Load current env vars
|
||||
load_dotenv()
|
||||
load_dotenv(override=True)
|
||||
|
||||
return {provider: os.getenv(provider) or "" for provider in providers}
|
||||
|
||||
|
@ -29,9 +26,6 @@ def get_local_api_keys(providers: List[str]) -> Dict[str, str]:
|
|||
|
||||
def save_local_api_keys(api_keys: Dict[str, str]) -> bool:
|
||||
"""Save API keys to .env file in local mode."""
|
||||
if config.ENV_MODE != EnvMode.LOCAL:
|
||||
return False
|
||||
|
||||
try:
|
||||
# Find .env file
|
||||
env_path = find_dotenv()
|
||||
|
@ -41,9 +35,8 @@ def save_local_api_keys(api_keys: Dict[str, str]) -> bool:
|
|||
|
||||
# Update each API key
|
||||
for key, value in api_keys.items():
|
||||
if value: # Only set if value is not empty
|
||||
set_key(env_path, key, value)
|
||||
logger.info(f"Updated {key} in .env file")
|
||||
set_key(env_path, key, value)
|
||||
logger.info(f"Updated {key} in .env file")
|
||||
|
||||
return True
|
||||
|
||||
|
|
|
@ -15,6 +15,7 @@ export default function PersonalAccountSettingsPage({
|
|||
// { name: "Teams", href: "/settings/teams" },
|
||||
{ name: 'Billing', href: '/settings/billing' },
|
||||
{ name: 'Usage Logs', href: '/settings/usage-logs' },
|
||||
{ name: 'LLM API Keys', href: '/settings/llm-api-keys' },
|
||||
];
|
||||
return (
|
||||
<>
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
import { isLocalMode } from "@/lib/config";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Shield } from "lucide-react";
|
||||
import { LLMApiKeys } from "@/components/api-keys/llm-api-keys";
|
||||
|
||||
export default function LLMKeysPage() {
|
||||
|
||||
return <LLMApiKeys />
|
||||
}
|
|
@ -0,0 +1,133 @@
|
|||
"use client";
|
||||
|
||||
import { Eye, EyeOff } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card";
|
||||
import { isLocalMode } from "@/lib/config";
|
||||
import { Input } from "../ui/input";
|
||||
import { Label } from "../ui/label";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { backendApi } from "@/lib/api-client";
|
||||
import { toast } from "sonner";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
interface APIKeyForm {
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
export function LLMApiKeys() {
|
||||
const queryClient = useQueryClient();
|
||||
const [visibleKeys, setVisibleKeys] = useState<Record<string, boolean>>({});
|
||||
const {data: apiKeys, isLoading} = useQuery({
|
||||
queryKey: ['api-keys'],
|
||||
queryFn: async() => {
|
||||
const response = await backendApi.get('/local-llm-keys');
|
||||
return response.data;
|
||||
},
|
||||
});
|
||||
|
||||
const { register, handleSubmit, formState: { errors, isDirty }, reset } = useForm<APIKeyForm>({
|
||||
defaultValues: apiKeys || {}
|
||||
});
|
||||
|
||||
const handleSave = async (data: APIKeyForm) => {
|
||||
updateApiKeys.mutate(data);
|
||||
}
|
||||
const updateApiKeys = useMutation({
|
||||
mutationFn: async (data: APIKeyForm) => {
|
||||
const response = await backendApi.post('/local-llm-keys', data);
|
||||
await queryClient.invalidateQueries({ queryKey: ['api-keys'] });
|
||||
return response.data;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
toast.success(data.message);
|
||||
},
|
||||
onError: () => {
|
||||
toast.error('Failed to update API keys');
|
||||
}
|
||||
});
|
||||
|
||||
const keysArray = apiKeys ? Object.entries(apiKeys).map(([key, value]) => ({
|
||||
id: key,
|
||||
name: key.replace(/_/g, " ").replace("KEY", "Key"),
|
||||
value: value
|
||||
})) : [];
|
||||
|
||||
useEffect(() => {
|
||||
if (apiKeys) {
|
||||
reset(apiKeys);
|
||||
}
|
||||
}, [apiKeys, reset]);
|
||||
|
||||
const toggleKeyVisibility = (keyId: string) => {
|
||||
setVisibleKeys(prev => ({
|
||||
...prev,
|
||||
[keyId]: !prev[keyId]
|
||||
}));
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return <Card>
|
||||
<CardHeader>
|
||||
<CardTitle>API Keys</CardTitle>
|
||||
<CardDescription>Loading...</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>;
|
||||
}
|
||||
|
||||
return <Card>
|
||||
<CardHeader>
|
||||
<CardTitle>API Keys</CardTitle>
|
||||
<CardDescription>
|
||||
{isLocalMode() ? (
|
||||
<>
|
||||
Manage your API keys for various Language Model providers.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
API key management is only available in local mode.
|
||||
</>
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
{isLocalMode() && (
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit(handleSave)} className="space-y-4">
|
||||
{keysArray && keysArray?.map((key: any) => (
|
||||
|
||||
<div key={key.id} className="space-y-2">
|
||||
<Label htmlFor={key.id}>{key.name}</Label>
|
||||
<div className="relative">
|
||||
<Input
|
||||
id={key.id}
|
||||
type={visibleKeys[key.id] ? 'text' : 'password'}
|
||||
placeholder={key.name}
|
||||
{...register(key.id)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="absolute right-0 top-0 h-full px-3"
|
||||
onClick={() => toggleKeyVisibility(key.id)}>
|
||||
{visibleKeys[key.id] ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</Button>
|
||||
</div>
|
||||
{errors[key.id] && <p className="text-red-500">{errors[key.id]?.message}</p>}
|
||||
</div>
|
||||
|
||||
))}
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="submit"
|
||||
variant="default"
|
||||
disabled={!isDirty}
|
||||
>Save</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
}
|
|
@ -17,6 +17,7 @@ import {
|
|||
AudioWaveform,
|
||||
Sun,
|
||||
Moon,
|
||||
Key,
|
||||
} from 'lucide-react';
|
||||
import { useAccounts } from '@/hooks/use-accounts';
|
||||
import NewTeamForm from '@/components/basejump/new-team-form';
|
||||
|
@ -48,6 +49,7 @@ import {
|
|||
} from '@/components/ui/dialog';
|
||||
import { createClient } from '@/lib/supabase/client';
|
||||
import { useTheme } from 'next-themes';
|
||||
import { isLocalMode } from '@/lib/config';
|
||||
|
||||
export function NavUserWithTeams({
|
||||
user,
|
||||
|
@ -286,6 +288,12 @@ export function NavUserWithTeams({
|
|||
Billing
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
{isLocalMode() && <DropdownMenuItem asChild>
|
||||
<Link href="/settings/llm-api-keys">
|
||||
<Key className="h-4 w-4" />
|
||||
LLM API Keys
|
||||
</Link>
|
||||
</DropdownMenuItem>}
|
||||
{/* <DropdownMenuItem asChild>
|
||||
<Link href="/settings">
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
|
|
|
@ -14,7 +14,7 @@ import {
|
|||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Check, ChevronDown, Search, AlertTriangle, Crown, ArrowUpRight, Brain, Plus, Edit, Trash, Cpu } from 'lucide-react';
|
||||
import { Check, ChevronDown, Search, AlertTriangle, Crown, ArrowUpRight, Brain, Plus, Edit, Trash, Cpu, Key } from 'lucide-react';
|
||||
import {
|
||||
ModelOption,
|
||||
SubscriptionStatus,
|
||||
|
@ -32,6 +32,7 @@ import { cn } from '@/lib/utils';
|
|||
import { useRouter } from 'next/navigation';
|
||||
import { isLocalMode } from '@/lib/config';
|
||||
import { CustomModelDialog, CustomModelFormData } from './custom-model-dialog';
|
||||
import Link from 'next/link';
|
||||
|
||||
interface CustomModel {
|
||||
id: string;
|
||||
|
@ -674,6 +675,22 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
|
|||
<div className="px-3 py-3 flex justify-between items-center">
|
||||
<span className="text-xs font-medium text-muted-foreground">All Models</span>
|
||||
{isLocalMode() && (
|
||||
<div className="flex items-center gap-1">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Link
|
||||
href="/settings/llm-api-keys"
|
||||
className="h-6 w-6 p-0 flex items-center justify-center"
|
||||
>
|
||||
<Key className="h-3.5 w-3.5" />
|
||||
</Link>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" className="text-xs">
|
||||
Manage API Keys
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
|
@ -694,6 +711,7 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
|
|||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{uniqueModels
|
||||
|
|
Loading…
Reference in New Issue