From 2ea13625ec2b1f8f21d53b5a0a5ec79f078d6461 Mon Sep 17 00:00:00 2001 From: Orionis Date: Thu, 29 Oct 2026 18:35:24 +0100 Subject: [PATCH] Correction de connexion Front --- prisma/schema.prisma | 19 +- src/index.ts | 8 +- src/routes/aiRoutes.ts | 6 +- src/services/aiOrchestrator.ts | 6 +- src/services/aiService.ts | 66 +++++++ src/services/remoteAiService.ts | 297 ++++++++++++++++++++++++++++++++ 6 files changed, 385 insertions(+), 17 deletions(-) create mode 100644 src/services/aiService.ts create mode 100644 src/services/remoteAiService.ts diff --git a/prisma/schema.prisma b/prisma/schema.prisma index c690a5c..51af4e0 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -45,11 +45,16 @@ model Service { } model GlobalSettings { - id Int @id @default(1) - notionToken String? - notionDbId String? - ollamaUrl String? // e.g., http://localhost:11434 - ollamaModel String? // e.g., qwen:7b - searxngUrl String? // e.g., http://localhost:8080 - aiLanguage String? // e.g., Français, English + id Int @id @default(1) + notionToken String? + notionDbId String? + aiMode String? // 'local' (Ollama + SearXNG) ou 'remote' (API clé) + ollamaUrl String? // e.g., http://localhost:11434 + ollamaModel String? // e.g., qwen:7b + searxngUrl String? // e.g., http://localhost:8080 + remoteProvider String? // 'mistral' | 'openai' | 'claude' | 'gemini' + remoteApiKey String? + remoteModel String? // e.g., mistral-large-latest, gpt-4o, claude-sonnet-4-5, gemini-2.0-flash + remoteApiUrl String? // URL de base optionnelle (proxy / instance privée) + aiLanguage String? // e.g., Français, English } diff --git a/src/index.ts b/src/index.ts index c85898b..39c16d6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -123,18 +123,18 @@ app.get('/api/settings', async (req, res) => { let settings = await prisma.globalSettings.findUnique({ where: { id: 1 } }); if (!settings) { settings = await prisma.globalSettings.create({ - data: { id: 1, notionToken: '', notionDbId: '', ollamaUrl: '', ollamaModel: '', searxngUrl: '', aiLanguage: 'Français' } + data: { id: 1, notionToken: '', notionDbId: '', aiMode: 'local', ollamaUrl: '', ollamaModel: '', searxngUrl: '', aiLanguage: 'Français' } }); } res.json(settings); }); app.post('/api/settings', async (req, res) => { - const { notionToken, notionDbId, ollamaUrl, ollamaModel, searxngUrl, aiLanguage } = req.body; + const { notionToken, notionDbId, aiMode, ollamaUrl, ollamaModel, searxngUrl, remoteProvider, remoteApiKey, remoteModel, remoteApiUrl, aiLanguage } = req.body; const settings = await prisma.globalSettings.upsert({ where: { id: 1 }, - update: { notionToken, notionDbId, ollamaUrl, ollamaModel, searxngUrl, aiLanguage }, - create: { id: 1, notionToken, notionDbId, ollamaUrl, ollamaModel, searxngUrl, aiLanguage } + update: { notionToken, notionDbId, aiMode, ollamaUrl, ollamaModel, searxngUrl, remoteProvider, remoteApiKey, remoteModel, remoteApiUrl, aiLanguage }, + create: { id: 1, notionToken, notionDbId, aiMode: aiMode || 'local', ollamaUrl, ollamaModel, searxngUrl, remoteProvider, remoteApiKey, remoteModel, remoteApiUrl, aiLanguage } }); res.json(settings); }); diff --git a/src/routes/aiRoutes.ts b/src/routes/aiRoutes.ts index 225d692..de63795 100644 --- a/src/routes/aiRoutes.ts +++ b/src/routes/aiRoutes.ts @@ -1,6 +1,6 @@ import { Router, Request, Response } from 'express'; import { prisma } from '../lib/prisma'; -import { chatWithOllama, chatWithOllamaStream, ChatMessage } from '../services/ollamaService'; +import { chatWithAI, chatWithAIStream, ChatMessage } from '../services/aiService'; import { AuthRequest } from '../middleware/authMiddleware'; const router = Router(); @@ -111,7 +111,7 @@ router.post('/chat', async (req: AuthRequest, res: Response) => { const settings = await prisma.globalSettings.findUnique({ where: { id: 1 } }); if (!settings) return res.status(500).json({ error: "Config manquante." }); - const aiContent = await chatWithOllama(history, settings); + const aiContent = await chatWithAI(history, settings); // 5. Sauvegarder la réponse de l'IA const aiMessage = await prisma.message.create({ @@ -200,7 +200,7 @@ router.post('/chat-stream', async (req: AuthRequest, res: Response) => { try { // Le streaming en lui même - const aiContent = await chatWithOllamaStream(history, settings, (chunk) => { + const aiContent = await chatWithAIStream(history, settings, (chunk) => { partialContent += chunk; if (!abortController.signal.aborted) { res.write(`data: ${JSON.stringify({ type: 'chunk', content: chunk })}\n\n`); diff --git a/src/services/aiOrchestrator.ts b/src/services/aiOrchestrator.ts index 303247f..f5c9873 100644 --- a/src/services/aiOrchestrator.ts +++ b/src/services/aiOrchestrator.ts @@ -1,6 +1,6 @@ import { GlobalSettings } from '@prisma/client'; import { searchWeb } from './searxngService'; -import { queryOllama, queryOllamaWithFallback } from './ollamaService'; +import { queryAI, queryAIWithFallback } from './aiService'; export interface AIAnalysisResult { status: 'Urgent' | 'Attention' | 'Normal'; @@ -62,7 +62,7 @@ ${logLines.join('\n')} Requête de recherche (uniquement la requête ou "NORMAL") :`; console.log(`🤖 [Orchestrator] Étape 1 : Synthèse pour recherche...`); - const searchTerms = await queryOllama(summaryPrompt, settings); + const searchTerms = await queryAI(summaryPrompt, settings); let webContext = ""; if (searchTerms && !searchTerms.includes("NORMAL") && settings.searxngUrl) { @@ -100,7 +100,7 @@ Réponds UNIQUEMENT sous forme d'un tableau JSON d'objets respectant ce format : ]`; console.log(`🤖 [Orchestrator] Étape 2 : Analyse finale du paquet...`); - const rawResponse = await queryOllamaWithFallback(finalPrompt, basePromptWithoutWeb(logLines), settings); + const rawResponse = await queryAIWithFallback(finalPrompt, basePromptWithoutWeb(logLines), settings); if (!rawResponse || rawResponse.trim() === "") { return logLines.map(line => ({ diff --git a/src/services/aiService.ts b/src/services/aiService.ts new file mode 100644 index 0000000..474165c --- /dev/null +++ b/src/services/aiService.ts @@ -0,0 +1,66 @@ +import { GlobalSettings } from '@prisma/client'; +import { + queryOllama, + queryOllamaWithFallback, + chatWithOllama, + chatWithOllamaStream, + ChatMessage +} from './ollamaService'; +import { remoteChat, remoteChatStream } from './remoteAiService'; + +export type { ChatMessage }; + +/** + * Dispatcher IA : route les requêtes vers Ollama (mode local) + * ou vers l'API distante configurée (Mistral, OpenAI, Claude, Gemini). + * Le mode est défini par GlobalSettings.aiMode : 'local' (défaut) ou 'remote'. + */ + +export function isRemoteMode(settings: GlobalSettings): boolean { + return settings.aiMode === 'remote'; +} + +/** Requête simple (prompt unique) vers l'IA locale ou distante. */ +export async function queryAI(prompt: string, settings: GlobalSettings): Promise { + if (isRemoteMode(settings)) { + return remoteChat([{ role: 'user', content: prompt }], settings); + } + return queryOllama(prompt, settings); +} + +/** Requête avec prompt de repli si la première réponse est vide. */ +export async function queryAIWithFallback( + mainPrompt: string, + fallbackPrompt: string, + settings: GlobalSettings +): Promise { + let response = await queryAI(mainPrompt, settings); + + if (!response || response.trim() === "") { + console.warn("⚠️ Premier essai IA vide, tentative de fallback..."); + response = await queryAI(fallbackPrompt, settings); + } + + return response; +} + +/** Chat (conversation complète) vers l'IA locale ou distante. */ +export async function chatWithAI(messages: ChatMessage[], settings: GlobalSettings): Promise { + if (isRemoteMode(settings)) { + return remoteChat(messages, settings); + } + return chatWithOllama(messages, settings); +} + +/** Chat streaming (SSE / NDJSON) vers l'IA locale ou distante. */ +export async function chatWithAIStream( + messages: ChatMessage[], + settings: GlobalSettings, + onChunk: (chunk: string) => void, + externalSignal?: AbortSignal +): Promise { + if (isRemoteMode(settings)) { + return remoteChatStream(messages, settings, onChunk, externalSignal); + } + return chatWithOllamaStream(messages, settings, onChunk, externalSignal); +} diff --git a/src/services/remoteAiService.ts b/src/services/remoteAiService.ts new file mode 100644 index 0000000..d0d521d --- /dev/null +++ b/src/services/remoteAiService.ts @@ -0,0 +1,297 @@ +import { GlobalSettings } from '@prisma/client'; +import { ChatMessage } from './ollamaService'; + +/** + * Service IA distant : support de Mistral, OpenAI (ChatGPT), Anthropic (Claude) et Google (Gemini). + * La configuration est stockée dans GlobalSettings (provider, clé API, modèle, URL de base optionnelle). + */ + +export type RemoteProvider = 'mistral' | 'openai' | 'claude' | 'gemini'; + +interface ProviderConfig { + defaultBaseUrl: string; + defaultModel: string; +} + +const PROVIDERS: Record = { + mistral: { defaultBaseUrl: 'https://api.mistral.ai/v1', defaultModel: 'mistral-large-latest' }, + openai: { defaultBaseUrl: 'https://api.openai.com/v1', defaultModel: 'gpt-4o' }, + claude: { defaultBaseUrl: 'https://api.anthropic.com/v1', defaultModel: 'claude-sonnet-4-5' }, + gemini: { defaultBaseUrl: 'https://generativelanguage.googleapis.com/v1beta', defaultModel: 'gemini-2.0-flash' }, +}; + +const TIMEOUT_MS = 300000; + +function resolveConfig(settings: GlobalSettings) { + const provider = (settings.remoteProvider as RemoteProvider) || 'mistral'; + const conf = PROVIDERS[provider]; + if (!conf) { + throw new Error(`Fournisseur IA distant inconnu : ${provider}`); + } + if (!settings.remoteApiKey) { + throw new Error("Configuration IA distante incomplète (clé API manquante)"); + } + return { + provider, + apiKey: settings.remoteApiKey, + model: settings.remoteModel || conf.defaultModel, + baseUrl: (settings.remoteApiUrl || conf.defaultBaseUrl).replace(/\/$/, ''), + }; +} + +/** Sépare les messages système du reste de la conversation (Claude et Gemini les exigent hors messages). */ +function splitSystemMessages(messages: ChatMessage[]) { + const systemParts = messages.filter(m => m.role === 'system').map(m => m.content); + const conversation = messages.filter(m => m.role !== 'system'); + return { systemPrompt: systemParts.join('\n\n'), conversation }; +} + +/** Parser SSE générique : découpe les chunks en lignes `data: ...` complètes. */ +async function consumeSseStream( + body: ReadableStream, + onData: (json: string) => void +) { + const reader = body.getReader(); + const decoder = new TextDecoder('utf-8'); + let buffer = ''; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; // On garde le fragment incomplet pour le prochain chunk + + for (const line of lines) { + const trimmed = line.trim(); + if (trimmed.startsWith('data:')) { + const payload = trimmed.slice(5).trim(); + if (payload && payload !== '[DONE]') { + onData(payload); + } + } + } + } +} + +// ---------- Mistral / OpenAI (API compatible OpenAI) ---------- + +async function openAiCompatibleChat( + messages: ChatMessage[], + settings: GlobalSettings, + stream: boolean, + onChunk?: (chunk: string) => void +): Promise { + const config = resolveConfig(settings); + const response = await fetch(`${config.baseUrl}/chat/completions`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${config.apiKey}`, + }, + body: JSON.stringify({ + model: config.model, + messages: messages.map(m => ({ role: m.role, content: m.content })), + stream, + }), + signal: AbortSignal.timeout(TIMEOUT_MS) + }); + + if (!response.ok) { + throw new Error(`Erreur API ${config.provider}: ${response.status} ${response.statusText}`); + } + + if (!stream || !response.body) { + const data = await response.json() as any; + return data.choices?.[0]?.message?.content || ""; + } + + let fullContent = ""; + await consumeSseStream(response.body, (json) => { + try { + const parsed = JSON.parse(json); + const delta = parsed.choices?.[0]?.delta?.content; + if (delta) { + fullContent += delta; + onChunk?.(delta); + } + } catch (e) { + // Ignore les fragments JSON partiels + } + }); + return fullContent; +} + +// ---------- Claude (Anthropic) ---------- + +async function claudeChat( + messages: ChatMessage[], + settings: GlobalSettings, + stream: boolean, + onChunk?: (chunk: string) => void +): Promise { + const config = resolveConfig(settings); + const { systemPrompt, conversation } = splitSystemMessages(messages); + + const response = await fetch(`${config.baseUrl}/messages`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-api-key': config.apiKey, + 'anthropic-version': '2023-06-01', + }, + body: JSON.stringify({ + model: config.model, + max_tokens: 8192, + ...(systemPrompt ? { system: systemPrompt } : {}), + messages: conversation.map(m => ({ + role: m.role === 'assistant' ? 'assistant' : 'user', + content: m.content, + })), + stream, + }), + signal: AbortSignal.timeout(TIMEOUT_MS) + }); + + if (!response.ok) { + throw new Error(`Erreur API Claude: ${response.status} ${response.statusText}`); + } + + if (!stream || !response.body) { + const data = await response.json() as any; + return (data.content || []) + .map((block: any) => block?.text || '') + .join(''); + } + + let fullContent = ""; + await consumeSseStream(response.body, (json) => { + try { + const parsed = JSON.parse(json); + if (parsed.type === 'content_block_delta' && parsed.delta?.text) { + fullContent += parsed.delta.text; + onChunk?.(parsed.delta.text); + } + } catch (e) { + // Ignore les fragments JSON partiels + } + }); + return fullContent; +} + +// ---------- Gemini (Google) ---------- + +async function geminiChat( + messages: ChatMessage[], + settings: GlobalSettings, + stream: boolean, + onChunk?: (chunk: string) => void +): Promise { + const config = resolveConfig(settings); + const { systemPrompt, conversation } = splitSystemMessages(messages); + + const action = stream ? 'streamGenerateContent?alt=sse' : 'generateContent'; + const response = await fetch(`${config.baseUrl}/models/${config.model}:${action}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-goog-api-key': config.apiKey, + }, + body: JSON.stringify({ + ...(systemPrompt ? { systemInstruction: { parts: [{ text: systemPrompt }] } } : {}), + contents: conversation.map(m => ({ + role: m.role === 'assistant' ? 'model' : 'user', + parts: [{ text: m.content }], + })), + }), + signal: AbortSignal.timeout(TIMEOUT_MS) + }); + + if (!response.ok) { + throw new Error(`Erreur API Gemini: ${response.status} ${response.statusText}`); + } + + const extractText = (parsed: any): string => + (parsed.candidates?.[0]?.content?.parts || []) + .map((part: any) => part?.text || '') + .join(''); + + if (!stream || !response.body) { + const data = await response.json() as any; + return extractText(data); + } + + let fullContent = ""; + await consumeSseStream(response.body, (json) => { + try { + const text = extractText(JSON.parse(json)); + if (text) { + fullContent += text; + onChunk?.(text); + } + } catch (e) { + // Ignore les fragments JSON partiels + } + }); + return fullContent; +} + +// ---------- API publique du service ---------- + +async function dispatch( + messages: ChatMessage[], + settings: GlobalSettings, + stream: boolean, + onChunk?: (chunk: string) => void, + externalSignal?: AbortSignal +): Promise { + const config = resolveConfig(settings); + + const run = async () => { + switch (config.provider) { + case 'mistral': + case 'openai': + return openAiCompatibleChat(messages, settings, stream, onChunk); + case 'claude': + return claudeChat(messages, settings, stream, onChunk); + case 'gemini': + return geminiChat(messages, settings, stream, onChunk); + default: + throw new Error(`Fournisseur IA distant non supporté : ${config.provider}`); + } + }; + + // Le timeout interne est combiné au signal d'annulation du client (bouton Stop) + if (externalSignal) { + return await Promise.race([ + run(), + new Promise((_, reject) => { + externalSignal.addEventListener('abort', () => { + reject(new DOMException('Aborted', 'AbortError')); + }); + }), + ]); + } + return run(); +} + +/** Chat distant sans streaming. */ +export async function remoteChat(messages: ChatMessage[], settings: GlobalSettings): Promise { + try { + return await dispatch(messages, settings, false); + } catch (error) { + console.error("Error querying remote AI:", error); + return ""; + } +} + +/** Chat distant avec streaming (SSE). Les erreurs sont relancées pour le bouton Stop. */ +export async function remoteChatStream( + messages: ChatMessage[], + settings: GlobalSettings, + onChunk: (chunk: string) => void, + externalSignal?: AbortSignal +): Promise { + return dispatch(messages, settings, true, onChunk, externalSignal); +}