File size: 12,512 Bytes
702292e
e831ff4
 
 
 
 
 
 
 
 
 
 
abcd79a
75d9414
abcd79a
019764a
 
75d9414
 
 
 
 
9e6c00e
 
75d9414
 
 
 
 
 
 
019764a
9a8d759
7109301
019764a
9a8d759
d4071bf
1f6fba1
d88cdc5
1f6fba1
75d9414
019764a
d4071bf
5c5b6bc
ea0a765
 
537a5db
ea0a765
 
 
 
 
 
 
537a5db
 
 
 
ea0a765
 
1f6fba1
9a8d759
a24791e
 
 
 
 
 
 
 
 
 
1f6fba1
 
 
9e6c00e
1f6fba1
 
a24791e
 
 
 
 
 
 
 
 
 
 
 
 
 
eb25aa8
 
 
 
a24791e
 
 
 
 
ea0a765
 
75d9414
 
9e6c00e
75d9414
 
 
 
 
 
 
 
1f6fba1
537a5db
 
1f6fba1
75d9414
 
 
1f6fba1
 
9e6c00e
1f6fba1
 
 
75d9414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537a5db
75d9414
 
 
 
 
 
 
 
 
 
 
 
9e6c00e
 
75d9414
 
a24791e
75d9414
 
1f6fba1
 
 
 
 
 
 
253550d
1f6fba1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253550d
 
 
fb6bee3
 
 
 
 
1f6fba1
253550d
1f6fba1
 
 
 
75d9414
 
 
 
 
 
 
 
 
537a5db
 
 
 
 
75d9414
 
537a5db
 
 
9e6c00e
a24791e
 
75d9414
f558ea3
 
7109301
d4071bf
7109301
 
9e6c00e
7109301
 
 
d88cdc5
019764a
5c5b6bc
d4071bf
e831ff4
 
 
 
 
d4071bf
 
e831ff4
 
 
d4071bf
e831ff4
f329fd2
 
702292e
 
c3e2b34
d4071bf
 
 
702292e
f558ea3
702292e
 
 
d4071bf
c3e2b34
d4071bf
 
702292e
f329fd2
d4071bf
f329fd2
d4071bf
 
f329fd2
d4071bf
 
f329fd2
 
d4071bf
f329fd2
 
 
d4071bf
f329fd2
d4071bf
 
f329fd2
 
d4071bf
f329fd2
 
 
002d869
 
 
 
d4071bf
f329fd2
c3e2b34
f329fd2
d4071bf
f329fd2
c3e2b34
f329fd2
c3e2b34
 
 
 
 
d4071bf
f329fd2
002d869
f329fd2
 
d4071bf
 
f329fd2
 
d4071bf
f329fd2
 
 
 
d4071bf
f329fd2
 
 
702292e
ddc6dad
 
50c168e
d70033b
 
 
 
af2012f
f329fd2
 
 
c3e2b34
50c168e
f329fd2
702292e
f329fd2
002d869
d4071bf
f329fd2
c3e2b34
a24791e
f329fd2
 
702292e
 
253550d
7109301
 
253550d
 
 
 
 
 
7109301
 
75d9414
e831ff4
 
75d9414
 
7109301
 
 
 
 
 
702292e
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
class ChatGPT{

    /* Eventos generados

    **********************/
    /* Eventos escuchados
        - chat:enviar
        - chat:eliminar

    **********************/


    definicion ={
        conversacion: [],
        usedTokens: 0
    };

    config = {
        temperature: 0.5,
        frequency_penalty: 0.0,
        presence_penalty: 0.0,
        useTool: true,
        assistant: "clasico",
        assistantPrompt: ""
    }

    tokens = {
        month: 0,
        total: 0
    }

    endpointChat = "/chat";
    challenge = null;
    windowHandlers = {}
    
    constructor(secHand){
        // Token JWT de ejecuci贸n
        this.secHand = secHand;
        
        this.obtenerToken();

        this.cargarEventos();


    }

    obtenerToken(){
        $.ajax({
            method: "POST",
            url: "/getToken",
            headers: {
                "Autorization": "Bearer " + this.token,
                'Content-Type': 'application/json',
            },
            data: JSON.stringify({
                fingerprint: this.secHand.fingerprint,
                public_key: this.secHand.publicKey
            }),
            timeout: 5000,
            dataType: "json"
        }).done((data) => {
            
            if(data.redirect){
                $("#inserted")[0].showModal()
                $("#inserted").html("<iframe src='"+data.redirect+"'>")
                $("#inserted").on("close", (event) =>{
                document.location.reload() 
                })
                
                return
            }

            this.secHand.sign(data.challenge).then(
                (result) => {
                    this.challenge = result
                    this.cargarConfigs(false, true);
                })
            this.token = data.token
        }).fail((data => {
            $("#inserted")[0].showModal()
            $("#inserted").html("<iframe src='/login'>")
            $("#inserted").on("close", (event) =>{
                document.location.reload() 
            })
            $("#inserted iframe").on("load", (event) =>{
                let location = event.target.contentDocument.location.pathname
                if(location == "/login"){
                    $("#inserted iframe")[0].contentWindow.data = {
                        fp: this.secHand.fingerprint,
                        pk: this.secHand.publicKey
                    }
                }
                if(location == "/"){
                    $("#inserted").html("")
                    $("#inserted")[0].close()
                    
                }
                
                
            })
        }))


    }

    cargarConfigs(abrirMenu, starting){
        self = this
        $.ajax({
            method: "POST",
            url: "/getConfigs",
            headers: {
                "Autorization": "Bearer " + this.token,
                'Content-Type': 'application/json',
            },
            data:JSON.stringify({
                challenge: this.challenge,
                fingerprint: this.secHand.fingerprint
            }),
            timeout: 5000,
            dataType: "json"
        }).done((data) => {
            let challenge = data["challenge"];
            delete data["challenge"];
            $("#assistant option[value='"+ data.assistant +"']")[0].selected=true
            this.secHand.sign(challenge).then((result) => {this.challenge = result;})
            this.config = data

            for(let confEl in data){
                if(typeof(data[confEl]) == "boolean"){
                    $("#"+confEl).prop("checked", data[confEl])
                }else{
                    $("#"+confEl).val(data[confEl])
                }
            }
            $(".range input").each(recalculateRanges)
            $(".range input").on("input", recalculateRanges)
            $(".item.parent input").on("change", function(){
                self.config[this.id] = this.checked
                if(!this.checked){
                    $(".item."+this.id+" input").prop("disabled", true)
                }else{
                    $(".item."+this.id+" input").prop("disabled", false)
                }
            })
            $(".range select").on("change", function(){
                self.config[this.id] = this.value
            })
            $("#tokensUsedMonth").text(data.tokens.month)
            $("#tokensUsedTotal").text(data.tokens.total)


            if(abrirMenu) $("#menu")[0].showModal()


            function recalculateRanges(){
                let value = (Math.round(this.value * 100) / 100).toFixed(2)
                $(this).parent().find("span").text(value);
                self.config[this.id] = parseFloat(value)  
            } 
            $(".item.parent input").trigger("change")

            if(starting){this.cargarChats()}
        })
        .fail(() => {
            document.location.href = "/";
        })
    }
    
    cargarEventos(){
        $(document).on("chat:enviar", (event, params) => {
            // Al enviar un mensaje, reintentos vuelve a 0
            this.reintentos = 0;
            this.enviar(params.ctx, params.ctx.conversacion);
        });
        $(document).on("chat:salvar", (event, params) => this.salvarChats(params.index, params.conversacion))
        $(document).on("chat:eliminar", (event, params) => this.eliminarChat(params.ctx, params.index))
        $(document).on("mostrar:opciones", () => this.mostrarOpciones())
        $("#nuevoChat").on("click", () => this.crearChat())  
        $("#menu .saveButton").on("click", () => this.salvarConfigs())
  
    }

    cargarChats(){
        let conversaciones = {}
        try{conversaciones = JSON.parse(localStorage.getItem("conversaciones"))||{}}catch{}

        if(!conversaciones || !Object.keys(conversaciones).length){
            this.crearChat()
            return
        }
        for(let key in conversaciones){
            if(!conversaciones[key]){
                continue
            }
            if(Object.keys(conversaciones[key]).indexOf('conversacion')!=-1){
                this.crearChat(key, conversaciones[key].conversacion)
            }else{
                this.crearChat(key, conversaciones[key])
            }
        }
        localStorage.setItem("conversaciones", JSON.stringify(conversaciones)) 

    }

    

    salvarConfigs(){
        $.ajax({
            method: "POST",
            url: "/setConfigs",
            headers: {
                "Autorization": "Bearer " + this.token,
                'Content-Type': 'application/json',
            },
            data: JSON.stringify(
                {...this.config,
                fingerprint: this.secHand.fingerprint,
                challenge: this.challenge,
            }),
            timeout: 5000,
            dataType: "json"
        }).done((data) => {
            this.secHand.sign(data.challenge).then((result) => {this.challenge = result})
            this.token = data.token
            this.config.assistantPrompt = data.assistantPrompt
        }).fail(() => {
            document.location.href = "/";
        })
    }

    crearChat(index, conversacion){
        // Se crea el nuevo manejador de ventana
        let uuid = this.generateRandID()
        this.windowHandlers[index||uuid] = new WindowHandler(
            conversacion||[], 
            index||uuid,
            this
        );
    }    

    eliminarChat(ctx, index){
        // Elimina el elemento de la lista de conversas y handler de ventanas
        delete this.windowHandlers[index]
        let conversaciones = {}
        try{conversaciones = JSON.parse(localStorage.getItem("conversaciones"))||{}}catch{}
        if(index in conversaciones){delete conversaciones[index]}
        localStorage.setItem("conversaciones", JSON.stringify(conversaciones)) 

        // Renumera las etiquetas, y selecciona la primera
        let labels = $(".tab-label")
        $(labels[0]).click();
 
        // Si no quedaron chats, crea uno vacio
        if(Object.keys(this.windowHandlers).length==0){
            this.crearChat()
        }
    }

    enviar(ctx, conversacion){
        // Envio de mensaje y manejo de comandos async

        // Crea un espacio temporal para almacenar los mensajes con el formato correcto
        let tempMensajes = [];
        for(let actMsg of conversacion){
            tempMensajes.push({role: actMsg.role, content: actMsg.content})
        }
        
        // Se anuncia la precarga
        ctx.respuestaInicio()

        //  Se almacena el contexto this
        let self = this;

        // Consumo de mensajes asincronos
        const consume = responseReader => {
            
            // Se lee la respuesta
            return responseReader.read().then(result => {

                //si finaliz贸 el mensaje, se termina el proceso
                if (result.done) { return; }

                // Se obtiene y decodifica el segmento
                const chunk = result.value;
                let text = new TextDecoder("utf-8").decode(chunk)
                
                // Se obtienen los mensajes y separan si son varios json juntos
                let responses = JSON.parse('[' + text.replace(/\}\{/g, '},{') + ']')
                
                // Por cada mensaje conseguido validamos el caso de accion
                for(let response of responses){
                    switch(response.comando){
                        // Se carga el nuevo token
                        case "token":
                            self.token = response.token;
                            break;
                        // Se carga el nuevo challenge
                        case "challenge":
                            this.secHand.sign(response.challenge).then((result) => {self.challenge = result})
                            break;
                        // Status del comportamiento
                        case "status":
                            ctx.respuestaStatus(response.status.mensaje, response.status.modo)
                            break;
                        // Mensaje a mostrar
                        case "mensaje":
                            ctx.respuestaMensaje(response.mensaje)
                            break;
                        // // Es una funci贸n
                        // case "function":
                        //     conversacion.push(response.function);
                        //     localStorage.setItem("conversaciones", JSON.stringify(self.conversaciones))
                        //     break;
                        // Algo fall贸
                        default:
                            console.log("???", response)
                    }
                }

                // Se consume la respuesta para continuar el proceso
                return consume(responseReader);
            }).catch(err =>{
                // Error
                console.log('algo paso', err)
            }); 
        }
            
        // Se ejecuta el request
        fetch(this.endpointChat, {
            method: "POST",
            body: JSON.stringify({
                messages: tempMensajes,
                challenge: this.challenge,
                fingerprint: this.secHand.fingerprint
            }),
            headers: {
                "Autorization": "Bearer " + this.token,
                'Content-Type': 'application/json',
            },
            timeout: 60000,
            dataType: "json"
        }).then(response => {
            if(response.status != 200){
                ctx.respuestaError(response)
                console.log("Error: ", response)
                return
            }
            return consume(response.body.getReader());
        }).catch(err =>{
            // Error
            console.log('Solicitud fallida', err)
            ctx.respuestaError(response)
            document.location.href = "/";
        }); 
       
    }

    salvarChats(index, conversacion){
        let conversaciones = {}
        try{conversaciones = JSON.parse(localStorage.getItem("conversaciones"))||{}}catch{}
        let temp = {}
        for (let i in conversaciones){
            temp[i]=conversaciones[i]
        }
        temp[index] = conversacion
        localStorage.setItem("conversaciones", JSON.stringify(temp)) 
    }

    

    mostrarOpciones(){
        this.cargarConfigs(true);
        
    }

    generateRandID(){
        return btoa((Math.random()*100**8)).replaceAll("=","").split("").reverse().join("");
    }

      
}