Skip to content

Commit

Permalink
REFACTOR
Browse files Browse the repository at this point in the history
  • Loading branch information
BorjaOteroFerreira committed Jan 6, 2025
1 parent 9d5529b commit 79f906b
Show file tree
Hide file tree
Showing 19 changed files with 22,588 additions and 1,710 deletions.
2 changes: 1 addition & 1 deletion FlaskApi.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def index(self):
models_list = self.get_models_list("models")
format_list = self.get_format_list()
chat_list = self.get_chat_list()
return render_template('index2.html', models_list=models_list, format_list=format_list, chat_list=chat_list)
return render_template('index.html', models_list=models_list, format_list=format_list, chat_list=chat_list)

def actualizar_historial(self):
nombre_chat = request.json.get('nombre_chat')
Expand Down
Binary file modified chroma_db/chroma.sqlite3
Binary file not shown.
4 changes: 3 additions & 1 deletion cortex.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ def _detectar_necesidad_herramienta(self, response, model):
r'función\s*\"([^"]+)\"\s+con\s+las\s+consultas\s+"([^"]+)"\s+y\s+"([^"]+)"',
r"\[Funcion '(\w+)' query='(.+?)'\]",
r"\[Funcion\s+'([^']+)'\s*,\s*query\s*=\s*'([^']+)' \]",
r"\[Funcion\s+'([^']+)'\s*,\s*Query\s*=\s*'([^']+)' \]"
r"\[Funcion\s+'([^']+)'\s*,\s*Query\s*=\s*'([^']+)' \]",
r"\[\s*Funcion:\s*'([^']+)',\s*query:\s*'([^']+)'\s*\]"


]

Expand Down
538 changes: 0 additions & 538 deletions static/js/chat a medias.js

This file was deleted.

1,052 changes: 540 additions & 512 deletions static/js/chat.js

Large diffs are not rendered by default.

96 changes: 51 additions & 45 deletions static/js/chat2.js → static/js/old_gui.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
//@author: Borja Otero Ferreira
class Chat {
constructor() {
this.tools= false;
this.rag = false;
const checkbox = document.getElementById('checkbox-3');
const checkboxrag = document.getElementById("checkbox-4");
const textarea = document.getElementById('user-input');
this.socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
this.socket.on('connect', () => this.onConnect());
this.systemMessage = 'Eres un asistente en español. Debes responder siemrpe en español';
this.conversationHistory = [{'role': 'system', 'content': this.systemMessage}];
this.conversationHistory = [{'role': 'system', 'content': 'Eres un asistente en español'}];
this.socket.on('assistant_response', (response) => this.assistantResponse(response));
this.socket.on('output_console', (response) => this.consoleOutputResponse(response));
this.socket.on('utilidades', (response) => this.cargarUtiles(response));
this.currentResponse = '';
this.library ='llama';
this.systemMessage = 'Eres un asistente en español. Debes responder siemrpe en español';
this.n_responses = 0;
this.popupCount = 0;
this.fullResponse = '';
this.totalTokens = 0;
this.totalTokensResponse =0;
this.conversationStarted = false;
this.memory=true;
this.chatId = ' ';
this.adjustTextareaHeight();
textarea.addEventListener('input', () => this.adjustTextareaHeight());
Expand All @@ -30,35 +26,8 @@ class Chat {
this.sendMessage();
}
});

// Agregar evento change a los checkbox
checkbox.addEventListener('change', () => {
this.tools = checkbox.checked;
});
checkboxrag.addEventListener('change', () => {
this.rag = checkboxrag.checked;
});
}

}
/** METHODS */
cargarUtiles(response) {
// Obtener el div donde se cargarán los resultados
var divResultados = document.getElementById('resultados'+ this.n_responses);
// Recorrer la lista de IDs de video recibidos
response.ids.forEach(function(id) {
// Crear un elemento iframe para cada ID de video
var iframe = document.createElement('iframe');
iframe.width = "64px";
iframe.height = "32px";
iframe.src = "https://www.youtube.com/embed/" + id;
iframe.frameborder = "0";
iframe.allow = "encrypted-media; picture-in-picture";
iframe.allowfullscreen = true;
// Agregar el iframe al div
divResultados.appendChild(iframe);
});
}

onConnect() {
console.log('Connected! ✅');
$('#stop-button').hide();
Expand All @@ -71,16 +40,19 @@ cargarUtiles(response) {
if (role === 'info')
divRespuesta = $('<div id="outputConsole" ><pre class='+role+'>ialab-suite@agent:~$ '+response.content+'</pre></div>');
divConsole.append(divRespuesta);

this.scrollToBottom(divConsole[0]);
}

assistantResponse(response) {
this.onAssistantResponse(response);

}

onAssistantResponse(response) {
var delta = '';
var choiceDelta =''

if (this.library === 'ollama'){
const responseData = response;
delta = responseData.content;
Expand Down Expand Up @@ -142,6 +114,7 @@ cargarUtiles(response) {
});
}


loadHistory(nombre_chat) {
nombre_chat = String(nombre_chat);
const self = this;
Expand All @@ -167,6 +140,7 @@ cargarUtiles(response) {
});
}


loadMessages(){
$('#chat-list').empty();
// Suponiendo que this.chatHistory contiene los mensajes
Expand Down Expand Up @@ -222,6 +196,7 @@ function sanitizeMessage(message) {
// Eliminar el elemento de la lista de conversaciones
const conversationListDiv = $('#conversations-list');
const elementToRemove = $('#' + chatId);

if (elementToRemove.length) {
elementToRemove.remove();
} else {
Expand All @@ -244,14 +219,17 @@ function sanitizeMessage(message) {
} else {
this.currentResponse += response;
}

const converter = new showdown.Converter();
this.response = converter.makeHtml(this.currentResponse);

const tableRegex = /(?:\|.*(?:\|).*)+\|/gs;
let htmlResponse = this.response.replace(tableRegex, (table) => {
const rows = table.trim().split('\n').map(row => row.trim().split('|').filter(cell => cell.trim() !== ''));

// Filtrar las filas que contienen guiones
const filteredRows = rows.filter(row => !row.some(cell => cell.includes('---')));

let htmlTable = '<table>';
for (let i = 0; i < filteredRows.length; i++) {
htmlTable += '<tr>';
Expand Down Expand Up @@ -313,14 +291,38 @@ function sanitizeMessage(message) {
}
var url = this.library === 'ollama' ? 'v1/chat/completions' : '/user_input';
var sanitizedUserMessage = this.escapeHtml(userMessage);
this.conversationHistory.push({'role': 'user', 'content': sanitizedUserMessage});

if(this.memory){
this.conversationHistory.push({'role': 'user', 'content': sanitizedUserMessage});
}
else{
var mensajeSistema = ""+
"Funciones disponibles: "+
"[Funcion: \'buscar_en_internet\' , query: \'url_o_consulta\' ]"+
"[Funcion: \'cripto_price\' , query: \'zilliqa,ethereum,\'"+
"[Funcion: \'video_search_tool\' , query: \'consulta\']"+
"Necesitas utilizar alguna para responder?"+
"responde con la herramienta a lanzar, ejemplo:"+
"supongamos que necesitas buscar el tiempo en internet , contestas:"+
"[Funcion: \'buscar_en_internet , query: \'tiempo proximos dias\' ]"+
"Puedes usar mas de una funcion. Responde solo con las funciones que usaras en el formato adecuado entre [], sin texto antes ni despues de los corchetes";
this.conversationHistory = [{'role':'system', 'content' : mensajeSistema}];
if(this.conversationHistory.length - 1 > 0){
var mensajeAsistente = this.conversationHistory[this.conversationHistory.length - 1];
this.conversationHistory.push(mensajeAsistente);
}
if(this.conversationHistory.length - 2 > 0 ){
var mensajeUsuario = this.conversationHistory[this.conversationHistory.length -2];
this.conversationHistory.push(mensajeUsuario);
}

this.conversationHistory.push({'role': 'user', 'content': sanitizedUserMessage});
}
const self = this;
self.conversationHistory[self.conversationHistory.length -1]['content'];;
self.conversationHistory[self.conversationHistory.length -1]['content'];/*+=". Puedes usar mas de una herramienta. Pero debe estar en la lista de herramientas."*/;
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify({ content: self.conversationHistory, tools: this.tools, rag: this.rag}), // Convertir a JSON
data: JSON.stringify({ content: self.conversationHistory}), // Convertir a JSON
contentType: 'application/json', // Asegura que el servidor entienda que es JSON
success: function (data) {
$('#stop-button').hide();
Expand All @@ -344,7 +346,7 @@ function sanitizeMessage(message) {
var conversationListDiv = $('#conversations-list');
var newChatHistory ='';
if(!buttonExists) {
newChatHistory = $("<div class='load-history' id='"+self.chatId+"'><button height='1em' width='1em' onclick=chat.deleteHistory('"+self.chatId+"')>❌</button><button class='btnLoadHistory' onclick=chat.loadHistory('"+self.chatId+"')>"+self.chatId+"</button></div>"); // $("<button class='load-history' onclick=chat.loadHistory('"+self.chatId+"')>📪 "+self.chatId+"</button>")
newChatHistory = $("<div class='load-history' id='"+self.chatId+"'><button height='1em' width='1em' onclick=chat.deleteHistory('"+self.chatId+"')>❌</button><button class='btnLoadHistory' onclick=chat.loadHistory('"+self.chatId+"')>"+self.chatId+"</button></div>"); // $("<button class='load-history' onclick=chat.loadHistory('"+self.chatId+"')>📪 "+self.chatId+"</button>")
conversationListDiv.prepend(newChatHistory);
}
self.guardarHistorial(self.chatId , self.conversationHistory);
Expand All @@ -362,16 +364,18 @@ function sanitizeMessage(message) {
$('#user-input').val('');
$('#user-input').focus();
var message = $('<div class="user-message-container-' + this.n_responses +
' user-message-container"><div id="chat-user-' + this.n_responses +
' user-message-container"><label for="chat-user-' + this.n_responses +
'">User</label><div id="chat-user-' + this.n_responses +
'" class="user-message user-message-' + this.n_responses + '">' +
sanitizedUserMessage + '</div></div>');
var chatList = $('#chat-list');

chatList.append(message);

var divAssistant = $('<div class="assistant-message-container-' + this.n_responses +
' assistant-message-container"><div id="contenedor_respuesta"><div id="chat-assistant-' + this.n_responses +
'" class="assistant-message"></div><div id="resultados'+ this.n_responses+ '" class="resultados"></div></div></div>');
' assistant-message-container"><label for="chat-assistant-' + this.n_responses +
'">Assistant<br></label><div id="chat-assistant-' + this.n_responses +
'" class="assistant-message"></div></div>');
chatList.append(divAssistant);

var shareButton = $('<button id="share" onclick="chat.shareChat(' + this.n_responses + ')">Share</button>');
Expand All @@ -385,10 +389,13 @@ function sanitizeMessage(message) {

// Método para agregar la respuesta completa al historial de conversación
addToConversationHistory() {
if (this.memory){
// Agregar la respuesta completa al historial de conversación
this.conversationHistory.push({'role': 'assistant', 'content': this.fullResponse});

// Reiniciar la respuesta completa para futuras conversaciones
this.fullResponse = '';
}
}

newChat() {
Expand Down Expand Up @@ -584,5 +591,4 @@ function sanitizeMessage(message) {
textarea.style.height = '0';
textarea.style.height = `${Math.min(textarea.scrollHeight, maxHeight)}px`;
}
}

}
Loading

0 comments on commit 79f906b

Please sign in to comment.