mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Fetch models from API
This commit is contained in:
1 parent
6a0d4b6f03
commit
44ae8b424b
4 files changed
+207
-1
No files matched your search
@@ -1,10 +1,12 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { Check, ChevronDown, Edit3 } from 'lucide-react';
|
||||
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ModelSelectorProps {
|
||||
@@ -26,9 +28,22 @@ export function ModelSelector({
|
||||
const [isCustomInput, setIsCustomInput] = useState(false);
|
||||
const [customValue, setCustomValue] = useState('');
|
||||
const { settings, addRecentlyUsedModel } = useAISettings();
|
||||
const { models, isLoading, error, refetch } = useProviderModels();
|
||||
|
||||
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
|
||||
|
||||
// Group models by provider
|
||||
const modelsByProvider = useMemo(() => {
|
||||
const groups: Record<string, typeof models> = {};
|
||||
for (const model of models) {
|
||||
if (!groups[model.provider]) {
|
||||
groups[model.provider] = [];
|
||||
}
|
||||
groups[model.provider].push(model);
|
||||
}
|
||||
return groups;
|
||||
}, [models]);
|
||||
|
||||
// Initialize with first recently used model if value is empty
|
||||
useEffect(() => {
|
||||
if (!value && recentlyUsedModels.length > 0) {
|
||||
@@ -140,6 +155,69 @@ export function ModelSelector({
|
||||
|
||||
{recentlyUsedModels.length > 0 && <CommandSeparator />}
|
||||
|
||||
{/* Loading state */}
|
||||
{isLoading && (
|
||||
<CommandGroup heading="Loading Models...">
|
||||
<div className="px-2 py-1.5">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
</div>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* Error state */}
|
||||
{error && !isLoading && (
|
||||
<CommandGroup heading="Error Loading Models">
|
||||
<div className="px-2 py-1.5 text-sm text-muted-foreground">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<div className="space-y-2">
|
||||
<p className="text-destructive">{error}</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={refetch}
|
||||
className="h-7 text-xs"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3 mr-1" />
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* Provider models */}
|
||||
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
|
||||
<div key={provider}>
|
||||
<CommandSeparator />
|
||||
<CommandGroup heading={provider.charAt(0).toUpperCase() + provider.slice(1)}>
|
||||
{providerModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model.fullId}
|
||||
value={model.fullId}
|
||||
onSelect={() => handleSelect(model.fullId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === model.fullId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">{model.name}</span>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{!isLoading && <CommandSeparator />}
|
||||
|
||||
<CommandGroup>
|
||||
<CommandItem
|
||||
value="__custom__"
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import OpenAI from 'openai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
|
||||
interface ProviderModel {
|
||||
id: string;
|
||||
name: string;
|
||||
provider: string;
|
||||
fullId: string; // provider/model format
|
||||
}
|
||||
|
||||
interface ModelFetchResult {
|
||||
models: ProviderModel[];
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
refetch: () => void;
|
||||
}
|
||||
|
||||
export function useProviderModels(): ModelFetchResult {
|
||||
const { settings } = useAISettings();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const {
|
||||
data: models = [],
|
||||
isLoading,
|
||||
refetch: queryRefetch,
|
||||
} = useQuery({
|
||||
queryKey: ['provider-models', settings.providers],
|
||||
queryFn: async () => {
|
||||
const allModels: ProviderModel[] = [];
|
||||
const errors: string[] = [];
|
||||
|
||||
// Fetch models from each configured provider
|
||||
for (const [providerKey, connection] of Object.entries(settings.providers)) {
|
||||
if (!connection.apiKey) {
|
||||
continue; // Skip providers without API keys
|
||||
}
|
||||
|
||||
try {
|
||||
const openai = new OpenAI({
|
||||
baseURL: connection.baseURL,
|
||||
apiKey: connection.apiKey,
|
||||
dangerouslyAllowBrowser: true,
|
||||
});
|
||||
|
||||
// Fetch models with timeout
|
||||
try {
|
||||
const response = await openai.models.list({
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
|
||||
// Transform models to our format
|
||||
const providerModels = response.data.map((model) => ({
|
||||
id: model.id,
|
||||
name: model.id,
|
||||
provider: providerKey,
|
||||
fullId: `${providerKey}/${model.id}`,
|
||||
}));
|
||||
|
||||
allModels.push(...providerModels);
|
||||
} catch (fetchError) {
|
||||
if (fetchError instanceof Error && fetchError.name === 'AbortError') {
|
||||
errors.push(`${providerKey}: Request timeout`);
|
||||
} else {
|
||||
throw fetchError;
|
||||
}
|
||||
}
|
||||
} catch (providerError) {
|
||||
console.warn(`Failed to fetch models from ${providerKey}:`, providerError);
|
||||
errors.push(
|
||||
`${providerKey}: ${
|
||||
providerError instanceof Error ? providerError.message : 'Unknown error'
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Set error state if there were any errors
|
||||
if (errors.length > 0) {
|
||||
setError(errors.join('; '));
|
||||
} else {
|
||||
setError(null);
|
||||
}
|
||||
|
||||
// Sort models by provider, then by name
|
||||
allModels.sort((a, b) => {
|
||||
if (a.provider !== b.provider) {
|
||||
return a.provider.localeCompare(b.provider);
|
||||
}
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return allModels;
|
||||
},
|
||||
enabled: Object.keys(settings.providers).length > 0,
|
||||
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
|
||||
retry: false, // Don't retry on failure
|
||||
});
|
||||
|
||||
const refetch = useCallback(() => {
|
||||
setError(null);
|
||||
queryRefetch();
|
||||
}, [queryRefetch]);
|
||||
|
||||
return {
|
||||
models,
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user