Correction de connexion Front
This commit is contained in:
1 parent
e6c55f57d7
commit
2ea13625ec
6 files changed
+385
-17
No files matched your search
+12
-7
@@ -45,11 +45,16 @@ model Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model GlobalSettings {
|
model GlobalSettings {
|
||||||
id Int @id @default(1)
|
id Int @id @default(1)
|
||||||
notionToken String?
|
notionToken String?
|
||||||
notionDbId String?
|
notionDbId String?
|
||||||
ollamaUrl String? // e.g., http://localhost:11434
|
aiMode String? // 'local' (Ollama + SearXNG) ou 'remote' (API clé)
|
||||||
ollamaModel String? // e.g., qwen:7b
|
ollamaUrl String? // e.g., http://localhost:11434
|
||||||
searxngUrl String? // e.g., http://localhost:8080
|
ollamaModel String? // e.g., qwen:7b
|
||||||
aiLanguage String? // e.g., Français, English
|
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
|
||||||
}
|
}
|
||||||
+4
-4
@@ -123,18 +123,18 @@ app.get('/api/settings', async (req, res) => {
|
|||||||
let settings = await prisma.globalSettings.findUnique({ where: { id: 1 } });
|
let settings = await prisma.globalSettings.findUnique({ where: { id: 1 } });
|
||||||
if (!settings) {
|
if (!settings) {
|
||||||
settings = await prisma.globalSettings.create({
|
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);
|
res.json(settings);
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post('/api/settings', async (req, res) => {
|
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({
|
const settings = await prisma.globalSettings.upsert({
|
||||||
where: { id: 1 },
|
where: { id: 1 },
|
||||||
update: { notionToken, notionDbId, ollamaUrl, ollamaModel, searxngUrl, aiLanguage },
|
update: { notionToken, notionDbId, aiMode, ollamaUrl, ollamaModel, searxngUrl, remoteProvider, remoteApiKey, remoteModel, remoteApiUrl, aiLanguage },
|
||||||
create: { id: 1, notionToken, notionDbId, ollamaUrl, ollamaModel, searxngUrl, aiLanguage }
|
create: { id: 1, notionToken, notionDbId, aiMode: aiMode || 'local', ollamaUrl, ollamaModel, searxngUrl, remoteProvider, remoteApiKey, remoteModel, remoteApiUrl, aiLanguage }
|
||||||
});
|
});
|
||||||
res.json(settings);
|
res.json(settings);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Router, Request, Response } from 'express';
|
import { Router, Request, Response } from 'express';
|
||||||
import { prisma } from '../lib/prisma';
|
import { prisma } from '../lib/prisma';
|
||||||
import { chatWithOllama, chatWithOllamaStream, ChatMessage } from '../services/ollamaService';
|
import { chatWithAI, chatWithAIStream, ChatMessage } from '../services/aiService';
|
||||||
import { AuthRequest } from '../middleware/authMiddleware';
|
import { AuthRequest } from '../middleware/authMiddleware';
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
@@ -111,7 +111,7 @@ router.post('/chat', async (req: AuthRequest, res: Response) => {
|
|||||||
const settings = await prisma.globalSettings.findUnique({ where: { id: 1 } });
|
const settings = await prisma.globalSettings.findUnique({ where: { id: 1 } });
|
||||||
if (!settings) return res.status(500).json({ error: "Config manquante." });
|
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
|
// 5. Sauvegarder la réponse de l'IA
|
||||||
const aiMessage = await prisma.message.create({
|
const aiMessage = await prisma.message.create({
|
||||||
@@ -200,7 +200,7 @@ router.post('/chat-stream', async (req: AuthRequest, res: Response) => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
// Le streaming en lui même
|
// Le streaming en lui même
|
||||||
const aiContent = await chatWithOllamaStream(history, settings, (chunk) => {
|
const aiContent = await chatWithAIStream(history, settings, (chunk) => {
|
||||||
partialContent += chunk;
|
partialContent += chunk;
|
||||||
if (!abortController.signal.aborted) {
|
if (!abortController.signal.aborted) {
|
||||||
res.write(`data: ${JSON.stringify({ type: 'chunk', content: chunk })}\n\n`);
|
res.write(`data: ${JSON.stringify({ type: 'chunk', content: chunk })}\n\n`);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { GlobalSettings } from '@prisma/client';
|
import { GlobalSettings } from '@prisma/client';
|
||||||
import { searchWeb } from './searxngService';
|
import { searchWeb } from './searxngService';
|
||||||
import { queryOllama, queryOllamaWithFallback } from './ollamaService';
|
import { queryAI, queryAIWithFallback } from './aiService';
|
||||||
|
|
||||||
export interface AIAnalysisResult {
|
export interface AIAnalysisResult {
|
||||||
status: 'Urgent' | 'Attention' | 'Normal';
|
status: 'Urgent' | 'Attention' | 'Normal';
|
||||||
@@ -62,7 +62,7 @@ ${logLines.join('\n')}
|
|||||||
Requête de recherche (uniquement la requête ou "NORMAL") :`;
|
Requête de recherche (uniquement la requête ou "NORMAL") :`;
|
||||||
|
|
||||||
console.log(`🤖 [Orchestrator] Étape 1 : Synthèse pour recherche...`);
|
console.log(`🤖 [Orchestrator] Étape 1 : Synthèse pour recherche...`);
|
||||||
const searchTerms = await queryOllama(summaryPrompt, settings);
|
const searchTerms = await queryAI(summaryPrompt, settings);
|
||||||
|
|
||||||
let webContext = "";
|
let webContext = "";
|
||||||
if (searchTerms && !searchTerms.includes("NORMAL") && settings.searxngUrl) {
|
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...`);
|
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() === "") {
|
if (!rawResponse || rawResponse.trim() === "") {
|
||||||
return logLines.map(line => ({
|
return logLines.map(line => ({
|
||||||
|
|||||||
@@ -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<string> {
|
||||||
|
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<string> {
|
||||||
|
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<string> {
|
||||||
|
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<string> {
|
||||||
|
if (isRemoteMode(settings)) {
|
||||||
|
return remoteChatStream(messages, settings, onChunk, externalSignal);
|
||||||
|
}
|
||||||
|
return chatWithOllamaStream(messages, settings, onChunk, externalSignal);
|
||||||
|
}
|
||||||
@@ -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<RemoteProvider, ProviderConfig> = {
|
||||||
|
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<Uint8Array>,
|
||||||
|
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<string> {
|
||||||
|
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<string> {
|
||||||
|
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<string> {
|
||||||
|
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<string> {
|
||||||
|
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<never>((_, reject) => {
|
||||||
|
externalSignal.addEventListener('abort', () => {
|
||||||
|
reject(new DOMException('Aborted', 'AbortError'));
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
return run();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Chat distant sans streaming. */
|
||||||
|
export async function remoteChat(messages: ChatMessage[], settings: GlobalSettings): Promise<string> {
|
||||||
|
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<string> {
|
||||||
|
return dispatch(messages, settings, true, onChunk, externalSignal);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user