- Iniziato a scrivere la CHATBOT...
This commit is contained in:
@@ -21,14 +21,13 @@ const globalTables = require('../tools/globalTables');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
const OpenAI = require("openai");
|
||||
const OpenAI = require('openai');
|
||||
|
||||
const { PassThrough } = require('stream');
|
||||
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
router.post('/getlist', authenticate_noerror, async function (req, res, next) {
|
||||
|
||||
|
||||
try {
|
||||
let idapp = req.body.idapp;
|
||||
|
||||
@@ -36,26 +35,23 @@ router.post('/getlist', authenticate_noerror, async function (req, res, next) {
|
||||
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
queryAIList
|
||||
queryAIList,
|
||||
});
|
||||
|
||||
} catch (e) {
|
||||
console.error('/getlist', e);
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
});
|
||||
|
||||
|
||||
async function getDeepSeekResponse(prompt, options) {
|
||||
try {
|
||||
const deepseek = new OpenAI({
|
||||
baseURL: 'https://api.deepseek.com/v1',
|
||||
apiKey: process.env.DS_API_KEY,
|
||||
defaultHeaders: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (!options.withexplain) {
|
||||
@@ -66,10 +62,10 @@ async function getDeepSeekResponse(prompt, options) {
|
||||
}
|
||||
|
||||
const completionStream = await deepseek.chat.completions.create({
|
||||
model: options.model || "deepseek-chat",
|
||||
model: options.model || 'deepseek-chat',
|
||||
messages: [
|
||||
{ role: "system", content: options?.contestsystem || "" },
|
||||
{ role: "user", content: prompt }
|
||||
{ role: 'system', content: options?.contestsystem || '' },
|
||||
{ role: 'user', content: prompt },
|
||||
],
|
||||
temperature: options?.temp || 0.3,
|
||||
max_tokens: options?.max_tokens || 1000,
|
||||
@@ -101,72 +97,147 @@ async function getDeepSeekResponse(prompt, options) {
|
||||
}
|
||||
|
||||
router.post('/ds', authenticate, async (req, res) => {
|
||||
|
||||
const { prompt, options } = req.body;
|
||||
|
||||
const isstream = (options && options?.stream)
|
||||
const isollama = options.model.startsWith('gemma3');
|
||||
|
||||
if (isstream) {
|
||||
// Se lo streaming è abilitato, restituiamo un flusso di dati
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
if (isollama) {
|
||||
// Endpoint per generare una risposta dal modello Ollama
|
||||
const { prompt } = req.body;
|
||||
// const model = "phi:3.8b-mini-4k"; // Modello predefinito
|
||||
const model = options.model;
|
||||
|
||||
if (!prompt) {
|
||||
return res.status(400).json({ error: 'Il prompt è richiesto.' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Ottieni il flusso di dati da DeepSeek
|
||||
const completionStream = await getDeepSeekResponse(prompt, options);
|
||||
|
||||
for await (const chunk of completionStream) {
|
||||
if (chunk.choices && chunk.choices[0]) {
|
||||
const data = JSON.stringify({ choice: chunk.choices[0] });
|
||||
res.write(`data: ${data}\n\n`);
|
||||
try {
|
||||
const msg = chunk.choices[0].delta.content;
|
||||
if (msg) {
|
||||
console.log(msg);
|
||||
// await tools.sleep(10000)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error: ' + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Chiamata all'API di Ollama
|
||||
const ollama = spawn('curl', [
|
||||
'-X',
|
||||
'POST',
|
||||
'http://localhost:11434/api/generate',
|
||||
'-H',
|
||||
'Content-Type: application/json',
|
||||
'-d',
|
||||
JSON.stringify({
|
||||
model: model,
|
||||
prompt: prompt,
|
||||
stream: false, // Imposta a true se vuoi una risposta in streaming
|
||||
}),
|
||||
]);
|
||||
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
let data = '';
|
||||
let error = '';
|
||||
|
||||
|
||||
} catch (error) {
|
||||
const errorstr = 'DeepSeek API Error:' + (error.response?.data || error.message)
|
||||
console.error(errorstr);
|
||||
|
||||
// In caso di errore durante lo streaming, invia un messaggio di errore
|
||||
const errorData = JSON.stringify({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: errorstr,
|
||||
ollama.stdout.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.write(`data: ${errorData}\n\n`);
|
||||
res.end();
|
||||
|
||||
ollama.stderr.on('data', (chunk) => {
|
||||
error += chunk;
|
||||
});
|
||||
|
||||
ollama.on('close', (code) => {
|
||||
if (code !== 0) {
|
||||
console.error(`Errore Ollama: ${error}`);
|
||||
return res.status(500).json({ error: 'Errore nella generazione del modello.' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Ollama restituisce una risposta JSON
|
||||
const response = JSON.parse(data);
|
||||
const risp = response?.error ? response?.error : response?.response;
|
||||
//res.json({ response: response.response }); // Invia solo la risposta al frontend
|
||||
|
||||
if (response?.error) {
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: risp,
|
||||
});
|
||||
} else {
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
choice: risp,
|
||||
});
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.error('Errore nel parsing della risposta di Ollama:', parseError);
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: 'Errore nella risposta del modello.',
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: 'Errore interno del server.',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
// Se lo streaming non è abilitato, restituisci la risposta completa
|
||||
const choice = await getDeepSeekResponse(prompt, options);
|
||||
const isstream = options && options?.stream;
|
||||
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
choice,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorstr = 'DeepSeek API Error:' + (error.response?.data || error.message)
|
||||
console.error(errorstr);
|
||||
if (isstream) {
|
||||
// Se lo streaming è abilitato, restituiamo un flusso di dati
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Cache-Control', 'no-cache');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
|
||||
// In caso di errore senza streaming, restituisci un errore standard
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: errorstr,
|
||||
});
|
||||
try {
|
||||
// Ottieni il flusso di dati da DeepSeek
|
||||
const completionStream = await getDeepSeekResponse(prompt, options);
|
||||
|
||||
for await (const chunk of completionStream) {
|
||||
if (chunk.choices && chunk.choices[0]) {
|
||||
const data = JSON.stringify({ choice: chunk.choices[0] });
|
||||
res.write(`data: ${data}\n\n`);
|
||||
try {
|
||||
const msg = chunk.choices[0].delta.content;
|
||||
if (msg) {
|
||||
console.log(msg);
|
||||
// await tools.sleep(10000)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error: ' + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
} catch (error) {
|
||||
const errorstr = 'API Error:' + (error.response?.data || error.message);
|
||||
console.error(errorstr);
|
||||
|
||||
// In caso di errore durante lo streaming, invia un messaggio di errore
|
||||
const errorData = JSON.stringify({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: errorstr,
|
||||
});
|
||||
res.write(`data: ${errorData}\n\n`);
|
||||
res.end();
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
// Se lo streaming non è abilitato, restituisci la risposta completa
|
||||
const choice = await getDeepSeekResponse(prompt, options);
|
||||
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_OK,
|
||||
choice,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorstr = 'API Error:' + (error.response?.data || error.message);
|
||||
console.error(errorstr);
|
||||
|
||||
// In caso di errore senza streaming, restituisci un errore standard
|
||||
return res.send({
|
||||
code: server_constants.RIS_CODE_ERR,
|
||||
error: errorstr,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -15,6 +15,8 @@ const Author = require('../models/author');
|
||||
|
||||
const tools = require('../tools/general');
|
||||
|
||||
const axios = require('axios');
|
||||
|
||||
router.post('/test-lungo', authenticate, (req, res) => {
|
||||
const timeout = req.body.timeout;
|
||||
|
||||
@@ -453,4 +455,19 @@ router.post('/search-books', authenticate, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/chatbot', authenticate, async (req, res) => {
|
||||
try {
|
||||
const response = await axios.post('http://localhost:5005/webhooks/rest/webhook', {
|
||||
sender: 'user',
|
||||
message: req.body.payload.message,
|
||||
});
|
||||
|
||||
res.json(response.data);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
res.status(500).send('Errore nella comunicazione con Rasa');
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
|
||||
Reference in New Issue
Block a user