This commit is contained in:
gpt-engineer-app[bot] 2025-12-04 00:43:38 +00:00
parent 3e56bb56cc
commit 7218d57061

View File

@ -1,6 +1,6 @@
import { useState, useRef, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Send, Bot, User, Loader2, Trash2, AlertTriangle, Maximize2, Minimize2, ChevronDown } from 'lucide-react';
import { Send, Bot, User, Loader2, Trash2, AlertTriangle, Maximize2, Minimize2, ChevronDown, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ScrollArea } from '@/components/ui/scroll-area';
@ -8,13 +8,22 @@ import { useSettings } from '@/contexts/SettingsContext';
import { useToast } from '@/hooks/use-toast';
import GlitchText from '@/components/GlitchText';
import MessageContent from '@/components/MessageContent';
import { AI_PROVIDERS, AIProvider, getProvider } from '@/lib/aiProviders';
import { AI_PROVIDERS, AIProvider, getProvider, CUSTOM_API_STORAGE_KEY } from '@/lib/aiProviders';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
interface Message {
id: string;
@ -23,6 +32,12 @@ interface Message {
timestamp: Date;
}
interface CustomApiConfig {
endpoint: string;
apiKey: string;
model: string;
}
const STORAGE_KEY = 'ai-chat-history';
const PROVIDER_KEY = 'ai-chat-provider';
@ -49,6 +64,19 @@ const AIChat = () => {
const stored = localStorage.getItem(PROVIDER_KEY);
return (stored as AIProvider) || 'pollinations';
});
const [customApiConfig, setCustomApiConfig] = useState<CustomApiConfig>(() => {
const stored = localStorage.getItem(CUSTOM_API_STORAGE_KEY);
if (stored) {
try {
return JSON.parse(stored);
} catch {
return { endpoint: '', apiKey: '', model: '' };
}
}
return { endpoint: '', apiKey: '', model: '' };
});
const [showCustomApiDialog, setShowCustomApiDialog] = useState(false);
const [tempCustomConfig, setTempCustomConfig] = useState<CustomApiConfig>({ endpoint: '', apiKey: '', model: '' });
const scrollRef = useRef<HTMLDivElement>(null);
const { playSound } = useSettings();
const { toast } = useToast();
@ -67,6 +95,13 @@ const AIChat = () => {
localStorage.setItem(PROVIDER_KEY, selectedProvider);
}, [selectedProvider]);
// Persist custom API config
useEffect(() => {
if (customApiConfig.endpoint || customApiConfig.apiKey) {
localStorage.setItem(CUSTOM_API_STORAGE_KEY, JSON.stringify(customApiConfig));
}
}, [customApiConfig]);
// Exit fullscreen on Escape key
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
@ -164,6 +199,23 @@ const AIChat = () => {
// Helper function to make API request with retry logic
const provider = getProvider(selectedProvider);
// For custom provider, use user's config
const apiEndpoint = selectedProvider === 'custom' ? customApiConfig.endpoint : provider.endpoint;
const apiKey = selectedProvider === 'custom' ? customApiConfig.apiKey : provider.apiKey;
const apiModel = selectedProvider === 'custom' ? customApiConfig.model : provider.model;
if (selectedProvider === 'custom' && (!customApiConfig.endpoint || !customApiConfig.apiKey)) {
toast({
title: 'Custom API not configured',
description: 'Please configure your custom API settings first.',
variant: 'destructive',
});
setMessages(prev => prev.filter(msg => msg.id !== assistantMessage.id));
setIsLoading(false);
return;
}
const makeRequest = async (retries = 3, delay = 1000): Promise<Response> => {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
@ -171,15 +223,15 @@ const AIChat = () => {
'Content-Type': 'application/json',
};
if (provider.requiresAuth && provider.apiKey) {
headers['Authorization'] = `Bearer ${provider.apiKey}`;
if ((provider.requiresAuth || selectedProvider === 'custom') && apiKey) {
headers['Authorization'] = `Bearer ${apiKey}`;
}
const response = await fetch(provider.endpoint, {
const response = await fetch(apiEndpoint, {
method: 'POST',
headers,
body: JSON.stringify({
model: provider.model,
model: apiModel,
messages: [
{ role: 'system', content: 'You are a helpful AI assistant with a hacker/cyberpunk personality. Keep responses concise and engaging. IMPORTANT: When sharing code examples, ALWAYS wrap them in markdown code blocks with the language specified, like ```python\ncode here\n``` or ```javascript\ncode here\n```. Never show code without proper markdown code block formatting.' },
...chatHistory,
@ -390,6 +442,10 @@ const AIChat = () => {
<DropdownMenuItem
key={provider.id}
onClick={() => {
if (provider.id === 'custom') {
setTempCustomConfig(customApiConfig);
setShowCustomApiDialog(true);
}
setSelectedProvider(provider.id);
playSound('click');
}}
@ -397,14 +453,34 @@ const AIChat = () => {
selectedProvider === provider.id ? 'text-primary' : 'text-foreground'
}`}
>
<div>
<div className="flex items-center gap-2 w-full">
<div className="flex-1">
<div>{provider.name}</div>
<div className="text-muted-foreground text-[10px]">{provider.description}</div>
</div>
{provider.id === 'custom' && (
<Settings className="w-3 h-3 text-muted-foreground" />
)}
</div>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{selectedProvider === 'custom' && (
<Button
variant="ghost"
size="sm"
onClick={() => {
setTempCustomConfig(customApiConfig);
setShowCustomApiDialog(true);
playSound('click');
}}
className="text-primary hover:bg-primary/20 font-pixel text-xs"
>
<Settings className="w-3 h-3 mr-1" />
Configure
</Button>
)}
</div>
<ScrollArea className="flex-1 border border-primary/30 rounded-lg p-4 mb-4 bg-background/50" ref={scrollRef}>
@ -504,6 +580,74 @@ const AIChat = () => {
)}
</Button>
</div>
{/* Custom API Configuration Dialog */}
<Dialog open={showCustomApiDialog} onOpenChange={setShowCustomApiDialog}>
<DialogContent className="bg-background border-primary/50">
<DialogHeader>
<DialogTitle className="font-pixel text-primary">Custom API Configuration</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="endpoint" className="font-pixel text-sm">API Endpoint</Label>
<Input
id="endpoint"
placeholder="https://api.example.com/v1/chat/completions"
value={tempCustomConfig.endpoint}
onChange={(e) => setTempCustomConfig(prev => ({ ...prev, endpoint: e.target.value }))}
className="font-pixel text-sm bg-background/50 border-primary/50"
/>
</div>
<div className="space-y-2">
<Label htmlFor="apiKey" className="font-pixel text-sm">API Key</Label>
<Input
id="apiKey"
type="password"
placeholder="sk-..."
value={tempCustomConfig.apiKey}
onChange={(e) => setTempCustomConfig(prev => ({ ...prev, apiKey: e.target.value }))}
className="font-pixel text-sm bg-background/50 border-primary/50"
/>
</div>
<div className="space-y-2">
<Label htmlFor="model" className="font-pixel text-sm">Model Name</Label>
<Input
id="model"
placeholder="gpt-4, claude-3, etc."
value={tempCustomConfig.model}
onChange={(e) => setTempCustomConfig(prev => ({ ...prev, model: e.target.value }))}
className="font-pixel text-sm bg-background/50 border-primary/50"
/>
</div>
<p className="text-xs text-muted-foreground font-pixel">
Your API key is stored locally in your browser and never sent to our servers.
</p>
</div>
<DialogFooter>
<Button
variant="ghost"
onClick={() => setShowCustomApiDialog(false)}
className="font-pixel text-sm"
>
Cancel
</Button>
<Button
onClick={() => {
setCustomApiConfig(tempCustomConfig);
setShowCustomApiDialog(false);
playSound('click');
toast({
title: 'Configuration Saved',
description: 'Custom API settings have been updated.',
});
}}
className="font-pixel text-sm bg-primary/20 border border-primary hover:bg-primary/30 text-primary"
>
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</motion.div>
);
};