mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Allow configuring multiple AI providers
This commit is contained in:
8 files changed
+415
-84
No files matched your search
@@ -1,24 +1,44 @@
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { AISettingsContext, type AISettings, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { AISettingsContext, type AISettings, type AIConnection, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface AISettingsProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: AISettings = {
|
||||
apiKey: '',
|
||||
baseUrl: 'https://openrouter.ai/api/v1',
|
||||
model: 'anthropic/claude-sonnet-4',
|
||||
providers: {},
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'ai-settings';
|
||||
|
||||
function migrateOldSettings(stored: unknown): AISettings {
|
||||
// Handle migration from old single-provider format
|
||||
if (stored && typeof stored === 'object' && 'apiKey' in stored && 'baseUrl' in stored) {
|
||||
const oldSettings = stored as { apiKey?: string; baseUrl?: string };
|
||||
return {
|
||||
providers: {
|
||||
openrouter: {
|
||||
baseURL: oldSettings.baseUrl || 'https://openrouter.ai/api/v1',
|
||||
apiKey: oldSettings.apiKey || '',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
// If it's already the new format or invalid, return as AISettings or default
|
||||
if (stored && typeof stored === 'object' && 'providers' in stored) {
|
||||
return stored as AISettings;
|
||||
}
|
||||
return DEFAULT_SETTINGS;
|
||||
}
|
||||
|
||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
const [settings, setSettings] = useState<AISettings>(() => {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored) {
|
||||
try {
|
||||
return { ...DEFAULT_SETTINGS, ...JSON.parse(stored) };
|
||||
const parsed = JSON.parse(stored);
|
||||
const migrated = migrateOldSettings(parsed);
|
||||
return { ...DEFAULT_SETTINGS, ...migrated };
|
||||
} catch {
|
||||
return DEFAULT_SETTINGS;
|
||||
}
|
||||
@@ -34,11 +54,47 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
setSettings(prev => ({ ...prev, ...newSettings }));
|
||||
};
|
||||
|
||||
const isConfigured = Boolean(settings.apiKey);
|
||||
const addProvider = (name: string, connection: AIConnection) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers: {
|
||||
...prev.providers,
|
||||
[name]: connection,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const removeProvider = (name: string) => {
|
||||
setSettings(prev => {
|
||||
const { [name]: removed, ...rest } = prev.providers;
|
||||
return {
|
||||
...prev,
|
||||
providers: rest,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const updateProvider = (name: string, connection: Partial<AIConnection>) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
providers: {
|
||||
...prev.providers,
|
||||
[name]: {
|
||||
...prev.providers[name],
|
||||
...connection,
|
||||
},
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const isConfigured = Object.entries(settings.providers).length > 0;
|
||||
|
||||
const contextValue: AISettingsContextType = {
|
||||
settings,
|
||||
updateSettings,
|
||||
addProvider,
|
||||
removeProvider,
|
||||
updateProvider,
|
||||
isConfigured,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Send, Settings, Play, CloudUpload, Loader2, MessageSquarePlus } from 'lucide-react';
|
||||
@@ -32,6 +33,7 @@ interface ChatPaneProps {
|
||||
|
||||
export function ChatPane({ projectId, projectName }: ChatPaneProps) {
|
||||
const [input, setInput] = useState('');
|
||||
const [providerModel, setProviderModel] = useState('openrouter/anthropic/claude-sonnet-4');
|
||||
const [isBuildLoading, setIsBuildLoading] = useState(false);
|
||||
const [isDeployLoading, setIsDeployLoading] = useState(false);
|
||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||
@@ -225,7 +227,7 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
setInput('');
|
||||
|
||||
try {
|
||||
await sendMessage(messageContent);
|
||||
await sendMessage(messageContent, providerModel.trim() || undefined);
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
// Error handling is done in the useAIChat hook
|
||||
@@ -429,17 +431,26 @@ BASE_DOMAIN=nostrdeploy.com`);
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t p-4">
|
||||
<div className="border-t p-4 space-y-3">
|
||||
<div className="flex gap-2">
|
||||
<Textarea
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onFocus={handleFirstInteraction}
|
||||
placeholder="Ask me to add features, edit files, or build your project..."
|
||||
className="min-h-[60px] resize-none"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<div className="flex-1 space-y-2">
|
||||
<Input
|
||||
value={providerModel}
|
||||
onChange={(e) => setProviderModel(e.target.value)}
|
||||
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
|
||||
className="text-sm font-mono"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<Textarea
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onFocus={handleFirstInteraction}
|
||||
placeholder="Ask me to add features, edit files, or build your project..."
|
||||
className="min-h-[60px] resize-none"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
|
||||
@@ -1,26 +1,65 @@
|
||||
import { useState } from 'react';
|
||||
import { Settings } from 'lucide-react';
|
||||
import { Settings, Plus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
export function AISettingsDialog() {
|
||||
const { settings, updateSettings, isConfigured } = useAISettings();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [localSettings, setLocalSettings] = useState(settings);
|
||||
const [localProviders, setLocalProviders] = useState(settings.providers);
|
||||
const [newProviderName, setNewProviderName] = useState('');
|
||||
|
||||
const handleSave = () => {
|
||||
updateSettings(localSettings);
|
||||
updateSettings({ providers: localProviders });
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setLocalSettings(settings);
|
||||
setLocalProviders(settings.providers);
|
||||
setNewProviderName('');
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleAddProvider = () => {
|
||||
if (!newProviderName.trim()) return;
|
||||
|
||||
const newProvider: AIConnection = {
|
||||
baseURL: '',
|
||||
apiKey: '',
|
||||
};
|
||||
|
||||
setLocalProviders(prev => ({
|
||||
...prev,
|
||||
[newProviderName.trim()]: newProvider,
|
||||
}));
|
||||
setNewProviderName('');
|
||||
};
|
||||
|
||||
const handleRemoveProvider = (name: string) => {
|
||||
setLocalProviders(prev => {
|
||||
const { [name]: removed, ...rest } = prev;
|
||||
return rest;
|
||||
});
|
||||
};
|
||||
|
||||
const handleUpdateProvider = (name: string, connection: Partial<AIConnection>) => {
|
||||
setLocalProviders(prev => ({
|
||||
...prev,
|
||||
[name]: {
|
||||
...prev[name],
|
||||
...connection,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const providerNames = Object.keys(localProviders);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
@@ -32,48 +71,111 @@ export function AISettingsDialog() {
|
||||
)}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogContent className="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>AI Settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure your AI provider settings. These settings are stored locally in your browser.
|
||||
Configure multiple AI providers. These settings are stored locally in your browser.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="apiKey">API Key</Label>
|
||||
<Input
|
||||
id="apiKey"
|
||||
type="password"
|
||||
placeholder="Enter your API key"
|
||||
value={localSettings.apiKey}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, apiKey: e.target.value })}
|
||||
/>
|
||||
{!localSettings.apiKey && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Required for AI functionality
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{/* Existing Providers */}
|
||||
{providerNames.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium">Configured Providers</h4>
|
||||
{providerNames.map((name) => (
|
||||
<Card key={name}>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base">{name}</CardTitle>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveProvider(name)}
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${name}-apiKey`}>API Key</Label>
|
||||
<Input
|
||||
id={`${name}-apiKey`}
|
||||
type="password"
|
||||
placeholder="Enter your API key"
|
||||
value={localProviders[name]?.apiKey || ''}
|
||||
onChange={(e) => handleUpdateProvider(name, { apiKey: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${name}-baseURL`}>Base URL</Label>
|
||||
<Input
|
||||
id={`${name}-baseURL`}
|
||||
placeholder="https://api.example.com/v1"
|
||||
value={localProviders[name]?.baseURL || ''}
|
||||
onChange={(e) => handleUpdateProvider(name, { baseURL: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{providerNames.length > 0 && <Separator />}
|
||||
|
||||
{/* Add New Provider */}
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-medium">Add New Provider</h4>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Provider name (e.g., openai, anthropic)"
|
||||
value={newProviderName}
|
||||
onChange={(e) => setNewProviderName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleAddProvider();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleAddProvider}
|
||||
disabled={!newProviderName.trim() || newProviderName.trim() in localProviders}
|
||||
size="sm"
|
||||
className="gap-2"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
{newProviderName.trim() in localProviders && (
|
||||
<p className="text-sm text-destructive">
|
||||
Provider with this name already exists
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="baseUrl">Base URL</Label>
|
||||
<Input
|
||||
id="baseUrl"
|
||||
placeholder="https://openrouter.ai/api/v1"
|
||||
value={localSettings.baseUrl}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, baseUrl: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="model">Model</Label>
|
||||
<Input
|
||||
id="model"
|
||||
placeholder="anthropic/claude-sonnet-4"
|
||||
value={localSettings.model}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, model: e.target.value })}
|
||||
/>
|
||||
|
||||
{/* Usage Instructions */}
|
||||
<div className="bg-muted/50 rounded-lg p-3 space-y-2">
|
||||
<h4 className="text-sm font-medium">Usage</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
In the chat, use the format <code className="bg-background px-1 rounded">provider/model</code> to specify which provider and model to use.
|
||||
</p>
|
||||
<div className="text-sm text-muted-foreground space-y-1">
|
||||
<p><strong>Examples:</strong></p>
|
||||
<ul className="list-disc list-inside ml-2 space-y-0.5">
|
||||
<li><code className="bg-background px-1 rounded">openrouter/anthropic/claude-sonnet-4</code></li>
|
||||
<li><code className="bg-background px-1 rounded">openai/gpt-4o</code></li>
|
||||
<li><code className="bg-background px-1 rounded">anthropic/claude-3-5-sonnet-20241022</code></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
Cancel
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { ArrowLeft, ArrowRight, Settings, Bot } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface AISettingsStepProps {
|
||||
onNext: () => void;
|
||||
@@ -13,15 +14,17 @@ interface AISettingsStepProps {
|
||||
}
|
||||
|
||||
export function AISettingsStep({ onNext, onPrevious, onSkip }: AISettingsStepProps) {
|
||||
const { settings, updateSettings } = useAISettings();
|
||||
const [localSettings, setLocalSettings] = useState(settings);
|
||||
const { settings, updateProvider } = useAISettings();
|
||||
const [localProvider, setLocalProvider] = useState<AIConnection>(
|
||||
settings.providers.openrouter || { baseURL: 'https://openrouter.ai/api/v1', apiKey: '' }
|
||||
);
|
||||
|
||||
const handleSave = () => {
|
||||
updateSettings(localSettings);
|
||||
updateProvider('openrouter', localProvider);
|
||||
onNext();
|
||||
};
|
||||
|
||||
const isValid = localSettings.apiKey.trim() && localSettings.baseUrl.trim() && localSettings.model.trim();
|
||||
const isValid = localProvider.apiKey.trim() && localProvider.baseURL.trim();
|
||||
|
||||
return (
|
||||
<div className="space-y-2 sm:space-y-4 mb-3 sm:mb-0">
|
||||
@@ -41,10 +44,10 @@ export function AISettingsStep({ onNext, onPrevious, onSkip }: AISettingsStepPro
|
||||
<CardHeader className="pb-2 sm:pb-3">
|
||||
<div className="flex items-center gap-1.5 sm:gap-2">
|
||||
<Settings className="h-3.5 w-3.5 sm:h-4 sm:w-4 text-primary" />
|
||||
<CardTitle className="text-base sm:text-lg">AI Provider</CardTitle>
|
||||
<CardTitle className="text-base sm:text-lg">OpenRouter Provider</CardTitle>
|
||||
</div>
|
||||
<CardDescription className="text-[10px] sm:text-xs">
|
||||
We recommend OpenRouter for easy setup
|
||||
We recommend OpenRouter for easy setup with multiple models
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 sm:space-y-3">
|
||||
@@ -55,8 +58,8 @@ export function AISettingsStep({ onNext, onPrevious, onSkip }: AISettingsStepPro
|
||||
id="apiKey"
|
||||
type="password"
|
||||
placeholder="sk-... or your-api-key"
|
||||
value={localSettings.apiKey}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, apiKey: e.target.value })}
|
||||
value={localProvider.apiKey}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, apiKey: e.target.value })}
|
||||
className="font-mono text-xs sm:text-sm h-8 sm:h-9"
|
||||
/>
|
||||
<p className="text-[10px] sm:text-xs text-muted-foreground">
|
||||
@@ -65,26 +68,22 @@ export function AISettingsStep({ onNext, onPrevious, onSkip }: AISettingsStepPro
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="baseUrl" className="text-xs sm:text-sm">Base URL *</Label>
|
||||
<Label htmlFor="baseURL" className="text-xs sm:text-sm">Base URL *</Label>
|
||||
<Input
|
||||
id="baseUrl"
|
||||
id="baseURL"
|
||||
placeholder="https://openrouter.ai/api/v1"
|
||||
value={localSettings.baseUrl}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, baseUrl: e.target.value })}
|
||||
value={localProvider.baseURL}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, baseURL: e.target.value })}
|
||||
className="text-xs sm:text-sm h-8 sm:h-9"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="model" className="text-xs sm:text-sm">Model *</Label>
|
||||
<Input
|
||||
id="model"
|
||||
placeholder="anthropic/claude-sonnet-4"
|
||||
value={localSettings.model}
|
||||
onChange={(e) => setLocalSettings({ ...localSettings, model: e.target.value })}
|
||||
className="text-xs sm:text-sm h-8 sm:h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="bg-muted/50 rounded-lg p-2 space-y-1">
|
||||
<p className="text-[10px] sm:text-xs font-medium">Usage in chat:</p>
|
||||
<p className="text-[10px] sm:text-xs text-muted-foreground">
|
||||
Use <code className="bg-background px-1 rounded">openrouter/anthropic/claude-sonnet-4</code> to specify model
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export interface AISettings {
|
||||
export interface AIConnection {
|
||||
baseURL: string;
|
||||
apiKey: string;
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
}
|
||||
|
||||
export interface AISettings {
|
||||
providers: Record<string, AIConnection>;
|
||||
}
|
||||
|
||||
export interface AISettingsContextType {
|
||||
settings: AISettings;
|
||||
updateSettings: (settings: Partial<AISettings>) => void;
|
||||
addProvider: (name: string, connection: AIConnection) => void;
|
||||
removeProvider: (name: string) => void;
|
||||
updateProvider: (name: string, connection: Partial<AIConnection>) => void;
|
||||
isConfigured: boolean;
|
||||
}
|
||||
|
||||
|
||||
+40
-6
@@ -3,6 +3,7 @@ import OpenAI from 'openai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
|
||||
// Use OpenAI's native message type
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
@@ -87,7 +88,7 @@ export function useAIChat({
|
||||
loadMessageHistory();
|
||||
}, [projectId, fs]);
|
||||
|
||||
const sendMessage = useCallback(async (content: string) => {
|
||||
const sendMessage = useCallback(async (content: string, providerModel?: string) => {
|
||||
if (!isConfigured || isLoading) return;
|
||||
|
||||
// Add user message
|
||||
@@ -117,10 +118,43 @@ export function useAIChat({
|
||||
});
|
||||
}
|
||||
|
||||
// Initialize OpenAI client
|
||||
// Parse provider and model if specified
|
||||
let connectionConfig;
|
||||
let modelName;
|
||||
|
||||
if (providerModel) {
|
||||
try {
|
||||
const parsed = parseProviderModel(providerModel, settings.providers);
|
||||
connectionConfig = parsed.connection;
|
||||
modelName = parsed.model;
|
||||
} catch (error) {
|
||||
// Add error message to chat
|
||||
const errorMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: `Error: ${error instanceof Error ? error.message : 'Failed to parse provider/model format'}`
|
||||
};
|
||||
addMessage(errorMessage);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Use first available provider as fallback
|
||||
const firstProvider = Object.keys(settings.providers)[0];
|
||||
if (!firstProvider || !settings.providers[firstProvider]?.apiKey) {
|
||||
const errorMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: 'Error: No provider/model specified and no configured providers available. Please specify a provider/model (e.g., "openrouter/anthropic/claude-sonnet-4") or configure a provider in settings.'
|
||||
};
|
||||
addMessage(errorMessage);
|
||||
return;
|
||||
}
|
||||
connectionConfig = settings.providers[firstProvider];
|
||||
modelName = 'gpt-3.5-turbo'; // Default fallback model
|
||||
}
|
||||
|
||||
// Initialize OpenAI client with parsed connection
|
||||
const openai = new OpenAI({
|
||||
baseURL: settings.baseUrl,
|
||||
apiKey: settings.apiKey,
|
||||
baseURL: connectionConfig.baseURL,
|
||||
apiKey: connectionConfig.apiKey,
|
||||
dangerouslyAllowBrowser: true
|
||||
});
|
||||
|
||||
@@ -147,7 +181,7 @@ export function useAIChat({
|
||||
|
||||
// Prepare chat completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
model: settings.model,
|
||||
model: modelName,
|
||||
messages: currentMessages,
|
||||
tools: tools && Object.keys(tools).length > 0 ? Object.values(tools) : undefined,
|
||||
tool_choice: tools && Object.keys(tools).length > 0 ? 'auto' : undefined,
|
||||
@@ -339,7 +373,7 @@ export function useAIChat({
|
||||
setIsLoading(false);
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
}, [isConfigured, isLoading, addMessage, messages, settings.baseUrl, settings.apiKey, settings.model, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps]);
|
||||
}, [isConfigured, isLoading, addMessage, messages, settings.providers, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
if (abortControllerRef.current) {
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseProviderModel } from './parseProviderModel';
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
describe('parseProviderModel', () => {
|
||||
const mockProviders: Record<string, AIConnection> = {
|
||||
openai: {
|
||||
baseURL: 'https://api.openai.com/v1',
|
||||
apiKey: 'sk-test-key',
|
||||
},
|
||||
openrouter: {
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: 'sk-or-test-key',
|
||||
},
|
||||
anthropic: {
|
||||
baseURL: 'https://api.anthropic.com',
|
||||
apiKey: 'sk-ant-test-key',
|
||||
},
|
||||
unconfigured: {
|
||||
baseURL: 'https://example.com/v1',
|
||||
apiKey: '',
|
||||
},
|
||||
};
|
||||
|
||||
it('should parse simple provider/model format', () => {
|
||||
const result = parseProviderModel('openai/gpt-4o', mockProviders);
|
||||
|
||||
expect(result.provider).toBe('openai');
|
||||
expect(result.model).toBe('gpt-4o');
|
||||
expect(result.connection).toEqual(mockProviders.openai);
|
||||
});
|
||||
|
||||
it('should parse complex model names with slashes', () => {
|
||||
const result = parseProviderModel('openrouter/anthropic/claude-sonnet-4', mockProviders);
|
||||
|
||||
expect(result.provider).toBe('openrouter');
|
||||
expect(result.model).toBe('anthropic/claude-sonnet-4');
|
||||
expect(result.connection).toEqual(mockProviders.openrouter);
|
||||
});
|
||||
|
||||
it('should handle model names with multiple slashes', () => {
|
||||
const result = parseProviderModel('openrouter/meta/llama-3.1-405b-instruct', mockProviders);
|
||||
|
||||
expect(result.provider).toBe('openrouter');
|
||||
expect(result.model).toBe('meta/llama-3.1-405b-instruct');
|
||||
expect(result.connection).toEqual(mockProviders.openrouter);
|
||||
});
|
||||
|
||||
it('should throw error for invalid format without slash', () => {
|
||||
expect(() => {
|
||||
parseProviderModel('invalidformat', mockProviders);
|
||||
}).toThrow('Invalid format. Use provider/model (e.g., "openai/gpt-4o")');
|
||||
});
|
||||
|
||||
it('should throw error for empty provider', () => {
|
||||
expect(() => {
|
||||
parseProviderModel('/gpt-4o', mockProviders);
|
||||
}).toThrow('Invalid format. Both provider and model must be specified');
|
||||
});
|
||||
|
||||
it('should throw error for empty model', () => {
|
||||
expect(() => {
|
||||
parseProviderModel('openai/', mockProviders);
|
||||
}).toThrow('Invalid format. Both provider and model must be specified');
|
||||
});
|
||||
|
||||
it('should throw error for unknown provider', () => {
|
||||
expect(() => {
|
||||
parseProviderModel('unknown/gpt-4o', mockProviders);
|
||||
}).toThrow('Provider "unknown" not found. Available providers: openai, openrouter, anthropic, unconfigured');
|
||||
});
|
||||
|
||||
it('should throw error for provider without API key', () => {
|
||||
expect(() => {
|
||||
parseProviderModel('unconfigured/some-model', mockProviders);
|
||||
}).toThrow('Provider "unconfigured" is not configured with an API key');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { AIConnection } from '@/contexts/AISettingsContext';
|
||||
|
||||
export interface ParsedProviderModel {
|
||||
provider: string;
|
||||
model: string;
|
||||
connection: AIConnection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a provider/model string and return the provider connection and model name
|
||||
* Format: provider/model (e.g., "openai/gpt-4o", "openrouter/anthropic/claude-sonnet-4")
|
||||
* The first slash separates the provider from the model
|
||||
*/
|
||||
export function parseProviderModel(
|
||||
providerModelString: string,
|
||||
providers: Record<string, AIConnection>
|
||||
): ParsedProviderModel {
|
||||
const firstSlashIndex = providerModelString.indexOf('/');
|
||||
|
||||
if (firstSlashIndex === -1) {
|
||||
throw new Error('Invalid format. Use provider/model (e.g., "openai/gpt-4o")');
|
||||
}
|
||||
|
||||
const provider = providerModelString.substring(0, firstSlashIndex);
|
||||
const model = providerModelString.substring(firstSlashIndex + 1);
|
||||
|
||||
if (!provider || !model) {
|
||||
throw new Error('Invalid format. Both provider and model must be specified');
|
||||
}
|
||||
|
||||
const connection = providers[provider];
|
||||
if (!connection) {
|
||||
throw new Error(`Provider "${provider}" not found. Available providers: ${Object.keys(providers).join(', ')}`);
|
||||
}
|
||||
|
||||
if (!connection.apiKey) {
|
||||
throw new Error(`Provider "${provider}" is not configured with an API key`);
|
||||
}
|
||||
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
connection,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user