Files
TradarrV2/frontend/src/pages/admin/AIProviders.tsx

507 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useEffect, useCallback } from 'react'
import { Plus, Trash2, Download, HardDrive, Cpu, ChevronUp, X } from 'lucide-react'
import { AIModelCatalog } from '@/components/AIModelCatalog'
import { adminApi, type AIProvider, type OllamaModelInfo, type ProviderConnectionStatus } from '@/api/admin'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Spinner } from '@/components/ui/spinner'
const PROVIDER_NAMES = ['openai', 'anthropic', 'gemini', 'ollama', 'claudecode'] as const
type ConnectionState = ProviderConnectionStatus | 'testing' | 'error'
const CONNECTION_MESSAGES: Record<ConnectionState, string> = {
testing: 'Test en cours…',
success: 'Connexion et authentification vérifiées.',
auth_check_unsupported: 'Authentification non vérifiée. Aucune synthèse n’a été générée.',
auth_rejected: 'Authentification refusée. Vérifiez les identifiants du fournisseur.',
unavailable: 'Fournisseur indisponible. Réessayez plus tard.',
error: 'Impossible de tester la connexion. Réessayez.',
}
const CUSTOM_MODELS_KEY = 'ollama_custom_models'
const KNOWN_OLLAMA_MODELS: { name: string; family: string; tags: { tag: string; size: string }[] }[] = [
{ name: 'qwen3', family: 'Qwen3', tags: [{ tag: '0.6b', size: '~0.4 GB' }, { tag: '1.7b', size: '~1.1 GB' }, { tag: '4b', size: '~2.6 GB' }, { tag: '8b', size: '~5.2 GB' }, { tag: '14b', size: '~9.3 GB' }, { tag: '32b', size: '~20 GB' }] },
{ name: 'qwen2.5', family: 'Qwen2.5', tags: [{ tag: '0.5b', size: '~0.4 GB' }, { tag: '1.5b', size: '~1 GB' }, { tag: '3b', size: '~2 GB' }, { tag: '7b', size: '~4.7 GB' }, { tag: '14b', size: '~9 GB' }, { tag: '32b', size: '~20 GB' }] },
{ name: 'llama3.2', family: 'Llama 3.2', tags: [{ tag: '1b', size: '~1.3 GB' }, { tag: '3b', size: '~2 GB' }] },
{ name: 'llama3.1', family: 'Llama 3.1', tags: [{ tag: '8b', size: '~4.9 GB' }, { tag: '70b', size: '~40 GB' }] },
{ name: 'gemma3', family: 'Gemma 3', tags: [{ tag: '1b', size: '~0.8 GB' }, { tag: '4b', size: '~3.3 GB' }, { tag: '12b', size: '~8 GB' }, { tag: '27b', size: '~17 GB' }] },
{ name: 'mistral', family: 'Mistral', tags: [{ tag: '7b', size: '~4.1 GB' }] },
{ name: 'phi4', family: 'Phi-4', tags: [{ tag: 'latest', size: '~9 GB' }] },
{ name: 'phi4-mini', family: 'Phi-4 Mini', tags: [{ tag: 'latest', size: '~2.5 GB' }] },
{ name: 'deepseek-r1', family: 'DeepSeek-R1', tags: [{ tag: '1.5b', size: '~1.1 GB' }, { tag: '7b', size: '~4.7 GB' }, { tag: '8b', size: '~4.9 GB' }, { tag: '14b', size: '~9 GB' }, { tag: '32b', size: '~20 GB' }] },
]
function formatSize(bytes: number): string {
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`
if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(0)} MB`
return `${bytes} B`
}
function loadCustomModels(): string[] {
try { return JSON.parse(localStorage.getItem(CUSTOM_MODELS_KEY) ?? '[]') } catch { return [] }
}
function saveCustomModels(models: string[]) {
localStorage.setItem(CUSTOM_MODELS_KEY, JSON.stringify(models))
}
// ── Confirmation dialog ────────────────────────────────────────────────────
function ConfirmDownloadDialog({ modelName, onConfirm, onCancel }: {
modelName: string
onConfirm: () => void
onCancel: () => void
}) {
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div className="bg-card border rounded-xl shadow-2xl p-6 w-full max-w-sm mx-4 space-y-4">
<div className="flex items-start justify-between">
<div>
<p className="font-semibold">Télécharger ce modèle ?</p>
<p className="text-sm text-muted-foreground mt-1">
<span className="font-mono text-foreground">{modelName}</span> sera téléchargé depuis Ollama Hub.
Le téléchargement peut prendre plusieurs minutes.
</p>
</div>
<button onClick={onCancel} className="text-muted-foreground hover:text-foreground ml-3 shrink-0">
<X className="h-4 w-4" />
</button>
</div>
<div className="flex gap-2 justify-end">
<Button variant="outline" size="sm" onClick={onCancel}>Annuler</Button>
<Button size="sm" onClick={onConfirm}>
<Download className="h-3 w-3 mr-1" /> Télécharger
</Button>
</div>
</div>
</div>
)
}
// ── Shared model catalogue ─────────────────────────────────────────────────
function ModelCatalogue({
installedNames,
pulling,
onPull,
}: {
installedNames: Set<string>
pulling: string | null
onPull: (name: string) => void
}) {
const [customName, setCustomName] = useState('')
const [pendingModel, setPendingModel] = useState<string | null>(null)
const [customModels, setCustomModels] = useState<string[]>(loadCustomModels)
// All model names in the hardcoded catalogue
const knownNames = new Set(
KNOWN_OLLAMA_MODELS.flatMap(f => f.tags.map(t => `${f.name}:${t.tag}`))
)
function requestPull(name: string) {
setPendingModel(name)
}
function confirmPull() {
if (!pendingModel) return
// If not in hardcoded catalogue, add to custom list
if (!knownNames.has(pendingModel)) {
const updated = [...new Set([...customModels, pendingModel])]
setCustomModels(updated)
saveCustomModels(updated)
}
onPull(pendingModel)
setPendingModel(null)
}
function submitCustom() {
const name = customName.trim()
if (!name) return
const fullName = name.includes(':') ? name : `${name}:latest`
setCustomName('')
requestPull(fullName)
}
// Families to display: hardcoded + custom entries
const customEntries = customModels.filter(m => !knownNames.has(m))
return (
<>
{pendingModel && (
<ConfirmDownloadDialog
modelName={pendingModel}
onConfirm={confirmPull}
onCancel={() => setPendingModel(null)}
/>
)}
<div className="space-y-4">
{/* Free-text input */}
<div>
<p className="text-xs font-semibold text-muted-foreground mb-1.5">Nom personnalisé</p>
<div className="flex gap-2">
<Input
className="h-8 text-sm font-mono"
placeholder="ex: llama3.2:3b, mymodel:latest…"
value={customName}
onChange={e => setCustomName(e.target.value)}
onKeyDown={e => e.key === 'Enter' && submitCustom()}
disabled={pulling !== null}
/>
<Button size="sm" className="h-8 shrink-0" onClick={submitCustom}
disabled={!customName.trim() || pulling !== null}>
<Download className="h-3 w-3" /> Installer
</Button>
</div>
</div>
{/* Custom models section */}
{customEntries.length > 0 && (
<div>
<p className="text-xs font-semibold text-muted-foreground mb-1.5">Personnalisés</p>
<div className="flex flex-wrap gap-1.5">
{customEntries.map(fullName => {
const installed = installedNames.has(fullName)
const isPulling = pulling === fullName
return <ModelTag key={fullName} fullName={fullName} size="?" installed={installed} isPulling={isPulling} pulling={pulling} onRequest={requestPull} />
})}
</div>
</div>
)}
{/* Hardcoded catalogue */}
<div className="space-y-3">
{KNOWN_OLLAMA_MODELS.map(family => (
<div key={family.name}>
<p className="text-xs font-semibold text-muted-foreground mb-1.5">{family.family}</p>
<div className="flex flex-wrap gap-1.5">
{family.tags.map(({ tag, size }) => {
const fullName = `${family.name}:${tag}`
const installed = installedNames.has(fullName)
const isPulling = pulling === fullName
return <ModelTag key={fullName} fullName={fullName} size={size} installed={installed} isPulling={isPulling} pulling={pulling} onRequest={requestPull} />
})}
</div>
</div>
))}
</div>
</div>
</>
)
}
function ModelTag({ fullName, size, installed, isPulling, pulling, onRequest }: {
fullName: string; size: string
installed: boolean; isPulling: boolean; pulling: string | null
onRequest: (name: string) => void
}) {
return (
<button
type="button"
disabled={installed || pulling !== null}
onClick={() => !installed && !isPulling && onRequest(fullName)}
className={[
'flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors',
installed
? 'border-primary/40 bg-primary/5 text-primary cursor-default'
: isPulling
? 'border-border bg-muted text-muted-foreground cursor-wait'
: pulling !== null
? 'border-border bg-background text-muted-foreground opacity-50 cursor-not-allowed'
: 'border-border bg-background hover:border-primary/60 hover:bg-primary/5 cursor-pointer',
].join(' ')}
>
{isPulling
? <><Spinner className="h-2.5 w-2.5" /> Téléchargement…</>
: installed
? <><span className="text-[10px]">✓</span> {fullName}</>
: <><Download className="h-2.5 w-2.5" /> {fullName} {size !== '?' && <span className="text-muted-foreground">{size}</span>}</>
}
</button>
)
}
// ── Ollama model manager card ──────────────────────────────────────────────
function OllamaModelsCard({ installedModels, onRefresh, onDelete }: {
installedModels: OllamaModelInfo[]
onRefresh: () => Promise<OllamaModelInfo[]>
onDelete: (name: string) => Promise<void>
}) {
const [showCatalogue, setShowCatalogue] = useState(false)
const [pulling, setPulling] = useState<string | null>(null)
const [deleting, setDeleting] = useState<string | null>(null)
const installedNames = new Set(installedModels.map(m => m.name))
async function pull(fullName: string) {
setPulling(fullName)
try {
await adminApi.pullOllamaModel(fullName)
await new Promise<void>(resolve => {
const iv = setInterval(async () => {
try {
const updated = await onRefresh()
if (updated.some(m => m.name === fullName)) { clearInterval(iv); resolve() }
} catch { /* ignore */ }
}, 4000)
setTimeout(() => { clearInterval(iv); resolve() }, 1800000)
})
} finally { setPulling(null) }
}
async function remove(name: string) {
setDeleting(name)
try { await onDelete(name) } finally { setDeleting(null) }
}
return (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2 text-base">
<HardDrive className="h-4 w-4" /> Modèles Ollama
</CardTitle>
<Button variant="outline" size="sm" onClick={() => setShowCatalogue(v => !v)}>
{showCatalogue ? <><ChevronUp className="h-3.5 w-3.5" /> Masquer</> : <><Download className="h-3.5 w-3.5" /> Installer</>}
</Button>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div>
<h3 className="text-sm font-semibold mb-2 flex items-center gap-1.5">
<Cpu className="h-3.5 w-3.5" /> Installés ({installedModels.length})
</h3>
{installedModels.length === 0 ? (
<p className="text-sm text-muted-foreground italic">Aucun modèle installé</p>
) : (
<div className="space-y-1.5">
{installedModels.map(m => (
<div key={m.name} className="flex items-center justify-between rounded-md border bg-muted/30 px-3 py-2">
<div>
<span className="font-mono text-sm font-medium">{m.name}</span>
<span className="ml-3 text-xs text-muted-foreground">
{formatSize(m.size)}
{m.details.parameter_size && <> · {m.details.parameter_size}</>}
{m.details.quantization_level && <> · {m.details.quantization_level}</>}
</span>
</div>
<Button variant="ghost" size="sm"
className="text-destructive hover:text-destructive h-7 w-7 p-0"
onClick={() => remove(m.name)} disabled={deleting === m.name}>
{deleting === m.name ? <Spinner className="h-3 w-3" /> : <Trash2 className="h-3 w-3" />}
</Button>
</div>
))}
</div>
)}
</div>
{showCatalogue && (
<div className="rounded-lg border bg-muted/30 p-4">
<p className="text-sm font-semibold mb-3">Catalogue</p>
<ModelCatalogue installedNames={installedNames} pulling={pulling} onPull={pull} />
</div>
)}
</CardContent>
</Card>
)
}
// ── Main Page ──────────────────────────────────────────────────────────────
export function AIProviders() {
const [providers, setProviders] = useState<AIProvider[]>([])
const [ollamaModels, setOllamaModels] = useState<OllamaModelInfo[]>([])
const [loading, setLoading] = useState(true)
const [showForm, setShowForm] = useState(false)
const [form, setForm] = useState({ name: 'openai', api_key: '', model: '', endpoint: '' })
const [editId, setEditId] = useState<string | null>(null)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const [connectionStates, setConnectionStates] = useState<Record<string, ConnectionState>>({})
const isOllamaForm = form.name === 'ollama'
const isClaudeCodeForm = form.name === 'claudecode'
const loadOllamaModels = useCallback(async (): Promise<OllamaModelInfo[]> => {
try {
const m = await adminApi.listOllamaModels()
const list = m ?? []
setOllamaModels(list)
return list
} catch (e) {
console.error('[ollama] error:', e)
return []
}
}, [])
const load = useCallback(() => {
return adminApi.listProviders().then(async providers => {
setProviders(providers ?? [])
await loadOllamaModels()
}).catch(() => setError('Impossible de charger les fournisseurs.'))
.finally(() => setLoading(false))
}, [loadOllamaModels])
useEffect(() => { load() }, [load])
async function testConnection(provider: AIProvider) {
setConnectionStates(states => ({ ...states, [provider.id]: 'testing' }))
try {
const result = await adminApi.testProvider(provider.id)
const status = result?.status
const state = status === 'success' || status === 'auth_rejected' || status === 'unavailable' || status === 'auth_check_unsupported' ? status : 'error'
setConnectionStates(states => ({ ...states, [provider.id]: state }))
} catch {
setConnectionStates(states => ({ ...states, [provider.id]: 'error' }))
}
}
async function save() {
setSaving(true); setError('')
try {
if (editId) { await adminApi.updateProvider(editId, form) }
else { await adminApi.createProvider(form) }
setConnectionStates({})
setShowForm(false); setEditId(null)
setForm({ name: 'openai', api_key: '', model: '', endpoint: '' })
setLoading(true); await load()
} catch { setError('Impossible d’enregistrer le fournisseur.'); setForm(f => ({ ...f, api_key: '' })) }
finally { setSaving(false) }
}
async function remove(id: string) {
if (!confirm('Supprimer ce fournisseur ?')) return
setError('')
try { await adminApi.deleteProvider(id); setLoading(true); await load() }
catch { setError('Impossible de supprimer ce fournisseur. Vérifiez les modèles et comptes qui l’utilisent.') }
}
function startEdit(p: AIProvider) {
setEditId(p.id); setForm({ name: p.name, api_key: '', model: p.model, endpoint: p.endpoint }); setShowForm(true)
}
async function deleteOllamaModel(name: string) {
await adminApi.deleteOllamaModel(name); await loadOllamaModels()
}
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold">Fournisseurs IA</h1>
<p className="text-muted-foreground text-sm">Gérez les connexions fournisseurs et le catalogue des modèles de synthèse. Chaque compte choisit son modèle dans Mes préférences.</p>
</div>
{error && !showForm && <p role="alert">{error}</p>}
{loading ? (
<div className="flex justify-center py-12"><Spinner /></div>
) : (
<>
<Card>
<CardHeader><CardTitle>Classement des articles</CardTitle></CardHeader>
<CardContent className="space-y-2">
<p className="font-medium">Laya, moteur fixe</p>
<p>Laya classe les articles pertinents. Le classement est distinct du modèle de synthèse choisi par chaque compte ; aucun fournisseur de synthèse ne remplace Laya.</p>
</CardContent>
</Card>
<AIModelCatalog providers={providers} />
{/* Providers list */}
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="text-base">Fournisseurs configurés</CardTitle>
<Button size="sm" onClick={() => { setShowForm(true); setEditId(null); setForm({ name: 'openai', api_key: '', model: '', endpoint: '' }) }}>
<Plus className="h-4 w-4" /> Ajouter
</Button>
</div>
</CardHeader>
<CardContent className="space-y-3">
{showForm && (
<div className="rounded-lg border p-4 space-y-4 bg-muted/30">
<p className="font-medium text-sm">{editId ? 'Modifier le fournisseur' : 'Nouveau fournisseur'}</p>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1">
<Label htmlFor="provider-name">Fournisseur</Label>
<Select id="provider-name" value={form.name} disabled={!!editId}
onChange={e => {
const name = e.target.value
setForm(f => ({ ...f, name, model: '', api_key: '', endpoint: name === 'ollama' ? 'http://ollama:11434' : '' }))
}}>
{PROVIDER_NAMES.map(n => <option key={n} value={n}>{n}</option>)}
</Select>
</div>
{!isOllamaForm && !isClaudeCodeForm && (
<div className="space-y-1">
<Label htmlFor="provider-key">Clé API {editId && <span className="text-muted-foreground text-xs">(vide = conserver)</span>}</Label>
<Input id="provider-key" type="password" autoComplete="new-password" placeholder="sk-…" value={form.api_key} onChange={e => setForm(f => ({ ...f, api_key: e.target.value }))} />
</div>
)}
{isOllamaForm && (
<div className="space-y-1">
<Label htmlFor="provider-endpoint">Endpoint</Label>
<Input id="provider-endpoint" value={form.endpoint || 'http://ollama:11434'} onChange={e => setForm(f => ({ ...f, endpoint: e.target.value }))} />
</div>
)}
</div>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<div className="flex gap-2">
<Button size="sm" onClick={save} disabled={saving}>{saving ? <Spinner className="h-4 w-4" /> : 'Enregistrer'}</Button>
<Button size="sm" variant="outline" onClick={() => { setShowForm(false); setEditId(null); setForm(f => ({ ...f, api_key: '' })) }}>Annuler</Button>
</div>
</div>
)}
{providers.length === 0 && !showForm && (
<p className="text-sm text-muted-foreground text-center py-4">Aucun fournisseur configuré</p>
)}
<p className="text-sm text-muted-foreground">Le test vérifie la connexion avec les identifiants enregistrés. Aucune synthèse n’est générée.</p>
{providers.map(p => (
<div key={p.id} data-provider-id={p.id} className="flex flex-wrap items-center gap-3 rounded-md border px-3 py-2.5">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-semibold capitalize text-sm">{p.name}</span>
{!p.has_key && p.name !== 'ollama' && p.name !== 'claudecode' && <Badge variant="outline" className="text-yellow-500 border-yellow-500 text-xs">Sans clé</Badge>}
</div>
<div className="text-xs text-muted-foreground flex gap-3 mt-0.5">
{p.endpoint && <span>{p.endpoint}</span>}
</div>
</div>
<div className="flex items-center gap-1.5">
<Button variant="outline" size="sm" className="h-7 px-2 text-xs"
aria-label={`Tester la connexion ${p.name}`}
aria-describedby={`connection-${p.id}`}
disabled={connectionStates[p.id] === 'testing' || (!p.has_key && p.name !== 'ollama' && p.name !== 'claudecode')}
onClick={() => testConnection(p)}>
{connectionStates[p.id] === 'testing' ? 'Test en cours…' : 'Tester'}
</Button>
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" disabled={connectionStates[p.id] === 'testing'} onClick={() => startEdit(p)}>Modifier</Button>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 text-destructive hover:text-destructive" disabled={connectionStates[p.id] === 'testing'} onClick={() => remove(p.id)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
<p id={`connection-${p.id}`} role="status" aria-label={`Connexion ${p.name}`} aria-live="polite" aria-atomic="true"
className="w-full text-sm">
{connectionStates[p.id] ? CONNECTION_MESSAGES[connectionStates[p.id]] :
(!p.has_key && p.name !== 'ollama' && p.name !== 'claudecode' ? 'Ajoutez une clé API pour tester la connexion.' : '')}
</p>
</div>
))}
</CardContent>
</Card>
{/* Ollama model manager — always shown so user can install even without provider configured */}
<OllamaModelsCard
installedModels={ollamaModels}
onRefresh={loadOllamaModels}
onDelete={deleteOllamaModel}
/>
</>
)}
</div>
)
}