feat(ai): test saved summary model generation (#43)
This commit is contained in:
@ -6,6 +6,8 @@ export interface AIProvider {
|
||||
}
|
||||
export type ProviderConnectionStatus = 'success' | 'auth_rejected' | 'unavailable' | 'auth_check_unsupported'
|
||||
|
||||
export type AIModelTestStatus = 'success' | 'empty_response' | 'auth_rejected' | 'model_unavailable' | 'rate_limited' | 'timeout' | 'unavailable'
|
||||
|
||||
export interface AIModelCatalogEntry { id: string; provider_id: string; provider?: string; model: string; enabled: boolean }
|
||||
export interface OllamaModelInfo {
|
||||
name: string; size: number; modified_at: string
|
||||
@ -42,6 +44,7 @@ export const adminApi = {
|
||||
|
||||
// User-selectable synthesis model catalogue
|
||||
listAIModelCatalog: () => api.get<AIModelCatalogEntry[]>('/admin/ai-models'),
|
||||
testAIModelCatalogEntry: (id: string) => api.post<{ status: AIModelTestStatus }>(`/admin/ai-models/${encodeURIComponent(id)}/test`),
|
||||
createAIModelCatalogEntry: (data: { provider_id: string; model: string }) => api.post<AIModelCatalogEntry>('/admin/ai-models', data),
|
||||
updateAIModelCatalogEntry: (id: string, data: { enabled: boolean }) => api.put<AIModelCatalogEntry>(`/admin/ai-models/${encodeURIComponent(id)}`, data),
|
||||
deleteAIModelCatalogEntry: (id: string) => api.delete<void>(`/admin/ai-models/${encodeURIComponent(id)}`),
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { useEffect, useState, useCallback, type FormEvent } from 'react'
|
||||
import { adminApi, type AIProvider, type AIModelCatalogEntry } from '@/api/admin'
|
||||
import { useEffect, useState, useCallback, useRef, type FormEvent } from 'react'
|
||||
import { adminApi, type AIProvider, type AIModelCatalogEntry, type AIModelTestStatus } from '@/api/admin'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@ -16,7 +17,39 @@ function isCatalogEntry(value: unknown): value is AIModelCatalogEntry {
|
||||
&& (entry.provider === undefined || typeof entry.provider === 'string')
|
||||
}
|
||||
|
||||
export function AIModelCatalog({ providers }: { providers: AIProvider[] }) {
|
||||
type ModelTestOutcome = AIModelTestStatus | 'testing' | 'busy'
|
||||
const MODEL_TEST_MESSAGES: Record<ModelTestOutcome, string> = {
|
||||
testing: 'Test du modèle en cours…',
|
||||
success: 'Test réussi : le modèle a renvoyé une réponse non vide.',
|
||||
empty_response: 'Le modèle a renvoyé une réponse vide.',
|
||||
auth_rejected: 'Authentification refusée par le fournisseur.',
|
||||
model_unavailable: 'Modèle inaccessible chez ce fournisseur.',
|
||||
rate_limited: 'Limite de requêtes atteinte. Réessayez plus tard.',
|
||||
timeout: 'Le test a dépassé le délai autorisé.',
|
||||
unavailable: 'Impossible de tester le modèle. Réessayez.',
|
||||
busy: 'Un test est déjà en cours chez ce fournisseur. Attendez sa fin avant de lancer un nouveau test.',
|
||||
}
|
||||
function boundedTestStatus(value: unknown): AIModelTestStatus {
|
||||
switch (value) {
|
||||
case 'success': case 'empty_response': case 'auth_rejected': case 'model_unavailable':
|
||||
case 'rate_limited': case 'timeout': case 'unavailable': return value
|
||||
default: return 'unavailable'
|
||||
}
|
||||
}
|
||||
|
||||
interface CatalogProps {
|
||||
providers: AIProvider[]
|
||||
busyProviderIds?: readonly string[]
|
||||
onTestingChange?: (providerId: string, testing: boolean) => void
|
||||
}
|
||||
|
||||
export function AIModelCatalog({ providers, busyProviderIds = [], onTestingChange }: CatalogProps) {
|
||||
const providerConfiguration = JSON.stringify(providers.map(provider => [provider.id, provider.name, provider.endpoint, provider.model, provider.has_key, provider.is_active]))
|
||||
const [testConfiguration, setTestConfiguration] = useState({ key: providerConfiguration, revision: 0 })
|
||||
const [testResults, setTestResults] = useState<Record<string, { status: ModelTestOutcome; config: string; revision: number }>>({})
|
||||
const [testingByProvider, setTestingByProvider] = useState<Record<string, string>>({})
|
||||
const testLocks = useRef(new Set<string>())
|
||||
const testButtons = useRef(new Map<string, HTMLButtonElement>())
|
||||
const [entries, setEntries] = useState<AIModelCatalogEntry[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [loadFailed, setLoadFailed] = useState(false)
|
||||
@ -39,9 +72,49 @@ export function AIModelCatalog({ providers }: { providers: AIProvider[] }) {
|
||||
.finally(() => setLoading(false)), [])
|
||||
useEffect(() => { void load() }, [load])
|
||||
|
||||
// Discard results permanently on configuration changes, including late replies.
|
||||
if (testConfiguration.key !== providerConfiguration) {
|
||||
setTestConfiguration({ key: providerConfiguration, revision: testConfiguration.revision + 1 })
|
||||
setTestResults({})
|
||||
}
|
||||
|
||||
function providerBusy(id: string) {
|
||||
return !!testingByProvider[id] || busyProviderIds.includes(id)
|
||||
}
|
||||
function configuration(entry: AIModelCatalogEntry) {
|
||||
const provider = providers.find(provider => provider.id === entry.provider_id)
|
||||
return JSON.stringify([entry.provider_id, entry.model, entry.enabled, provider?.name, provider?.endpoint, provider?.model, provider?.has_key, provider?.is_active])
|
||||
}
|
||||
async function test(entry: AIModelCatalogEntry) {
|
||||
if (busy || loadFailed || providerBusy(entry.provider_id) || testLocks.current.has(entry.provider_id)) return
|
||||
const trigger = testButtons.current.get(entry.id)
|
||||
const keepFocus = document.activeElement === trigger
|
||||
const config = configuration(entry)
|
||||
const revision = testConfiguration.revision
|
||||
const remember = (status: ModelTestOutcome) => setTestResults(current => ({ ...current, [entry.id]: { status, config, revision } }))
|
||||
testLocks.current.add(entry.provider_id)
|
||||
setTestingByProvider(current => ({ ...current, [entry.provider_id]: entry.id }))
|
||||
remember('testing')
|
||||
onTestingChange?.(entry.provider_id, true)
|
||||
try {
|
||||
const result = await adminApi.testAIModelCatalogEntry(entry.id)
|
||||
remember(boundedTestStatus(result?.status))
|
||||
} catch (error) {
|
||||
remember(error instanceof ApiError && error.status === 409 ? 'busy'
|
||||
: error instanceof ApiError && error.status === 404 ? 'model_unavailable' : 'unavailable')
|
||||
} finally {
|
||||
testLocks.current.delete(entry.provider_id)
|
||||
setTestingByProvider(current => { const next = { ...current }; delete next[entry.provider_id]; return next })
|
||||
onTestingChange?.(entry.provider_id, false)
|
||||
if (keepFocus) setTimeout(() => {
|
||||
if (trigger?.isConnected && !trigger.disabled && document.activeElement === document.body) trigger.focus()
|
||||
}, 0)
|
||||
}
|
||||
}
|
||||
|
||||
async function save(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
if (busy || loadFailed || !providerId || !model.trim()) return
|
||||
if (busy || loadFailed || !providerId || !model.trim() || providerBusy(providerId) || testLocks.current.has(providerId)) return
|
||||
setBusy(true); setError(''); setNotice('')
|
||||
try {
|
||||
await adminApi.createAIModelCatalogEntry({ provider_id: providerId, model: model.trim() })
|
||||
@ -52,11 +125,12 @@ export function AIModelCatalog({ providers }: { providers: AIProvider[] }) {
|
||||
}
|
||||
|
||||
async function change(entry: AIModelCatalogEntry, remove: boolean) {
|
||||
if (busy || loadFailed) return
|
||||
if (busy || loadFailed || providerBusy(entry.provider_id) || testLocks.current.has(entry.provider_id)) return
|
||||
setBusy(true); setError(''); setNotice('')
|
||||
try {
|
||||
if (remove) await adminApi.deleteAIModelCatalogEntry(entry.id)
|
||||
else await adminApi.updateAIModelCatalogEntry(entry.id, { enabled: !entry.enabled })
|
||||
setTestResults(current => { const next = { ...current }; delete next[entry.id]; return next })
|
||||
if (await load()) setNotice(remove ? 'Modèle supprimé du catalogue.' : 'Disponibilité du modèle mise à jour.')
|
||||
} catch (error) {
|
||||
setError(error && typeof error === 'object' && 'status' in error && error.status === 409
|
||||
@ -69,19 +143,35 @@ export function AIModelCatalog({ providers }: { providers: AIProvider[] }) {
|
||||
<CardHeader><CardTitle>Catalogue des modèles de synthèse</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p>Les modèles activés sont proposés à tous les comptes. Chaque utilisateur choisit sa configuration personnelle ; aucun choix global ne remplace cette sélection.</p>
|
||||
<p id="model-test-help" className="text-sm text-muted-foreground">Le test envoie une courte demande au modèle exact et vérifie qu’une réponse non vide est reçue. Il peut consommer des tokens facturés. La réponse n’est pas affichée. Un modèle désactivé peut être testé sans être activé.</p>
|
||||
{loading && <p role="status">Chargement du catalogue…</p>}
|
||||
{error && <div><p role="alert">{error}</p><Button disabled={busy} variant="outline" onClick={() => { setLoading(true); setError(''); void load() }}>Recharger le catalogue</Button></div>}
|
||||
{notice && <p role="status">{notice}</p>}
|
||||
{!loading && <>
|
||||
{!loadFailed && entries.length === 0 && <p>Aucun modèle configuré.</p>}
|
||||
<ul className="space-y-3">{entries.map(entry => <li key={entry.id} className="rounded-md border p-3 space-y-2 break-words">
|
||||
<p>{entry.provider ?? providers.find(provider => provider.id === entry.provider_id)?.name ?? 'Fournisseur indisponible'} · {entry.model}</p>
|
||||
<p>{entry.enabled ? 'Proposé aux comptes' : 'Désactivé'}</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" disabled={busy || loadFailed} onClick={() => void change(entry, false)}>{entry.enabled ? 'Désactiver' : 'Activer'}</Button>
|
||||
<Button variant="outline" disabled={busy || loadFailed} onClick={() => void change(entry, true)}>Supprimer le modèle</Button>
|
||||
</div>
|
||||
</li>)}</ul>
|
||||
<ul className="space-y-3">{entries.map(entry => {
|
||||
const provider = entry.provider ?? providers.find(provider => provider.id === entry.provider_id)?.name ?? 'Fournisseur indisponible'
|
||||
const storedResult = testResults[entry.id]
|
||||
const result = storedResult?.config === configuration(entry) && storedResult.revision === testConfiguration.revision ? storedResult : undefined
|
||||
const providerTesting = providerBusy(entry.provider_id)
|
||||
const message = providerTesting
|
||||
? testingByProvider[entry.provider_id] === entry.id ? MODEL_TEST_MESSAGES.testing : `Un test est déjà en cours chez ${provider}.`
|
||||
: result ? MODEL_TEST_MESSAGES[result.status] : ''
|
||||
return <li key={entry.id} className="rounded-md border p-3 space-y-2 break-words">
|
||||
<p>{provider} · {entry.model}</p>
|
||||
<p>{entry.enabled ? 'Proposé aux comptes' : 'Désactivé'}</p>
|
||||
<div className="flex flex-wrap gap-2" aria-busy={providerTesting}>
|
||||
<Button variant="outline" disabled={busy || loadFailed || providerTesting}
|
||||
ref={element => { if (element) testButtons.current.set(entry.id, element); else testButtons.current.delete(entry.id) }}
|
||||
aria-label={`Tester le modèle ${entry.model} chez ${provider}`}
|
||||
aria-describedby={`model-test-help model-test-${entry.id}`}
|
||||
onClick={() => void test(entry)}>{testingByProvider[entry.provider_id] === entry.id ? 'Test en cours…' : 'Tester'}</Button>
|
||||
<Button variant="outline" disabled={busy || loadFailed || providerTesting} onClick={() => void change(entry, false)}>{entry.enabled ? 'Désactiver' : 'Activer'}</Button>
|
||||
<Button variant="outline" disabled={busy || loadFailed || providerTesting} onClick={() => void change(entry, true)}>Supprimer le modèle</Button>
|
||||
</div>
|
||||
<p id={`model-test-${entry.id}`} role="status" aria-label={`Test du modèle ${entry.model} chez ${provider}`} aria-live="polite" aria-atomic="true">{message}</p>
|
||||
</li>
|
||||
})}</ul>
|
||||
{!loadFailed && <form aria-label="Ajouter un modèle" onSubmit={save} className="space-y-3">
|
||||
<Label htmlFor="catalog-provider">Connexion fournisseur</Label>
|
||||
<Select id="catalog-provider" required disabled={busy} value={providerId} onChange={event => setProviderId(event.target.value)}>
|
||||
@ -89,9 +179,9 @@ export function AIModelCatalog({ providers }: { providers: AIProvider[] }) {
|
||||
{providers.map(provider => <option key={provider.id} value={provider.id}>{provider.name}</option>)}
|
||||
</Select>
|
||||
<Label htmlFor="catalog-model">Identifiant du modèle</Label>
|
||||
<Input id="catalog-model" required maxLength={256} value={model} disabled={busy} onChange={event => setModel(event.target.value)} />
|
||||
<Input id="catalog-model" required maxLength={256} value={model} disabled={busy || providerBusy(providerId)} onChange={event => setModel(event.target.value)} />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="submit" disabled={busy || !providerId || !model.trim()}>{busy ? 'Enregistrement…' : 'Ajouter au catalogue'}</Button>
|
||||
<Button type="submit" disabled={busy || !providerId || !model.trim() || providerBusy(providerId)}>{busy ? 'Enregistrement…' : 'Ajouter au catalogue'}</Button>
|
||||
</div>
|
||||
</form>}
|
||||
</>}
|
||||
|
||||
@ -321,6 +321,7 @@ export function AIProviders() {
|
||||
const [editId, setEditId] = useState<string | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [modelTestingProviders, setModelTestingProviders] = useState<string[]>([])
|
||||
const [connectionStates, setConnectionStates] = useState<Record<string, ConnectionState>>({})
|
||||
|
||||
const isOllamaForm = form.name === 'ollama'
|
||||
@ -361,6 +362,7 @@ export function AIProviders() {
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (editId && modelTestingProviders.includes(editId)) return
|
||||
setSaving(true); setError('')
|
||||
try {
|
||||
if (editId) { await adminApi.updateProvider(editId, form) }
|
||||
@ -405,7 +407,9 @@ export function AIProviders() {
|
||||
<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} />
|
||||
<AIModelCatalog providers={providers}
|
||||
busyProviderIds={[...modelTestingProviders, ...Object.keys(connectionStates).filter(id => connectionStates[id] === 'testing'), ...(saving && editId ? [editId] : [])]}
|
||||
onTestingChange={(id, testing) => setModelTestingProviders(current => testing ? [...new Set([...current, id])] : current.filter(value => value !== id))} />
|
||||
|
||||
{/* Providers list */}
|
||||
<Card>
|
||||
@ -447,7 +451,7 @@ export function AIProviders() {
|
||||
</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" onClick={save} disabled={saving || !!(editId && modelTestingProviders.includes(editId))}>{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>
|
||||
@ -474,12 +478,12 @@ export function AIProviders() {
|
||||
<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')}
|
||||
disabled={modelTestingProviders.includes(p.id) || 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)}>
|
||||
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" disabled={modelTestingProviders.includes(p.id) || 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={modelTestingProviders.includes(p.id) || connectionStates[p.id] === 'testing'} onClick={() => remove(p.id)}>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user