Fetch models from API

This commit is contained in:
Alex Gleason committed 2025-08-25 19:19:28 -05:00
1 parent fd485ac1e9
commit 1415008d67
4 files changed
+207 -1

No files matched your search

+15
View File
@@ -88,6 +88,7 @@
"@tailwindcss/typography": "^0.5.15",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/path-browserify": "^1.0.3",
@@ -3615,6 +3616,20 @@
}
}
},
"node_modules/@testing-library/user-event": {
"version": "14.6.1",
"resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.1.tgz",
"integrity": "sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12",
"npm": ">=6"
},
"peerDependencies": {
"@testing-library/dom": ">=7.21.4"
}
},
"node_modules/@tsconfig/node10": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz",
+1
View File
@@ -90,6 +90,7 @@
"@tailwindcss/typography": "^0.5.15",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@types/jszip": "^3.4.0",
"@types/node": "^22.5.5",
"@types/path-browserify": "^1.0.3",
+79 -1
View File
@@ -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__"
+112
View File
@@ -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,
};
}