MGLDZM commited on
Commit
a11e69b
·
1 Parent(s): f00a5ac

feat: async load

Browse files
Files changed (3) hide show
  1. .gitignore +1 -0
  2. main.py +13 -18
  3. static/js/main.js +35 -42
.gitignore CHANGED
@@ -1,3 +1,4 @@
1
  .history/
2
  .vscode/
3
  __pycache__/
 
 
1
  .history/
2
  .vscode/
3
  __pycache__/
4
+ keys/
main.py CHANGED
@@ -212,28 +212,27 @@ async def chat_stream(data = Depends(validate_token)):
212
  chunk_size = 1024
213
  chunk_body = ""
214
  total_tokens = 0
215
- yield json.dumps({"type": "role", "role": "assistant"})
216
  for chunk in response:
 
217
  delta = chunk["choices"][0]["delta"]
218
- total_tokens += 1
219
- if "content" not in delta: continue
 
220
 
221
- chunk_body += delta["content"]
222
- # if "``" not in chunk_body:
223
- # chunk_body = re.sub(r'`([^`]+)`', r'<b>\1</b>', chunk_body)
224
 
225
- if len(chunk_body) < chunk_size:
226
- continue
227
 
228
-
229
  if "`" in chunk_body:
230
  try:
231
  chunk_body += next(response)["choices"][0]["delta"]["content"]
232
  except StopIteration as e:
233
  pass
234
 
235
-
236
-
237
  if "``" in chunk_body:
238
  while not re.findall(r'(```[^`]+```)', chunk_body):
239
  try:
@@ -242,16 +241,12 @@ async def chat_stream(data = Depends(validate_token)):
242
  break
243
 
244
  codigo = re.findall(r'(```[^`]+```)', chunk_body)[0]
245
- print("codigo:", codigo)
246
  chunk_body = chunk_body.replace(codigo, procesar_codigo(codigo))
247
 
248
-
249
- #chunk_body = re.sub(r'`([^`]+)`', r'<b>\1</b>', chunk_body)
250
-
251
- yield json.dumps({"type": "content", "content": chunk_body})
252
  chunk_body = ""
253
 
254
- yield json.dumps({"type": "config", "token": token, "config":config, "tokens":total_tokens})
255
 
256
- return StreamingResponse(__streamer())
257
 
 
212
  chunk_size = 1024
213
  chunk_body = ""
214
  total_tokens = 0
215
+ yield '{"type": "role", "role": "assistant", "content": "'
216
  for chunk in response:
217
+
218
  delta = chunk["choices"][0]["delta"]
219
+ if chunk["choices"][0]["finish_reason"] != "stop":
220
+ total_tokens += 1
221
+ if "content" not in delta: continue
222
 
223
+ chunk_body += delta["content"]
224
+ if "``" not in chunk_body and "`" in chunk_body:
225
+ chunk_body = re.sub(r'`([^`]+)`', r'<b>\1</b>', chunk_body)
226
 
227
+ if len(chunk_body) < chunk_size:
228
+ continue
229
 
 
230
  if "`" in chunk_body:
231
  try:
232
  chunk_body += next(response)["choices"][0]["delta"]["content"]
233
  except StopIteration as e:
234
  pass
235
 
 
 
236
  if "``" in chunk_body:
237
  while not re.findall(r'(```[^`]+```)', chunk_body):
238
  try:
 
241
  break
242
 
243
  codigo = re.findall(r'(```[^`]+```)', chunk_body)[0]
 
244
  chunk_body = chunk_body.replace(codigo, procesar_codigo(codigo))
245
 
246
+ yield json.dumps(chunk_body)[1:-1]
 
 
 
247
  chunk_body = ""
248
 
249
+ yield f'", "token": "{token}", ' + '"config":' + json.dumps(config) +', ' + f'"tokens":{total_tokens}' +'}'
250
 
251
+ return StreamingResponse(__streamer(), media_type="application/json")
252
 
static/js/main.js CHANGED
@@ -5,7 +5,7 @@ let config = {
5
  temperature: 1.0,
6
  frequency_penalty: 0.0,
7
  presence_penalty: 0.0,
8
- stream: false
9
  }
10
  $(document).ready(function() {
11
 
@@ -27,7 +27,7 @@ $(document).ready(function() {
27
  $("#input-text").keypress(function(event){
28
  if (!event.shiftKey && event.keyCode === 13) {
29
  event.preventDefault();
30
- if(stream){
31
  sendMessageStream();
32
  }else{
33
  sendMessage();
@@ -38,7 +38,7 @@ $(document).ready(function() {
38
 
39
  $("#input-send").click(function(event) {
40
  event.preventDefault();
41
- if(stream){
42
  sendMessageStream();
43
  }else{
44
  sendMessage();
@@ -53,7 +53,7 @@ $(document).ready(function() {
53
  temperature: 1.0,
54
  frequency_penalty: 0.0,
55
  presence_penalty: 0.0,
56
- stream: false
57
  }
58
  $("#input-text").val("");
59
  recaularTextbox();
@@ -193,16 +193,16 @@ function sendMessage() {
193
  config: config
194
  }),
195
  success: function(data) {
196
- token = data.token;
197
  let clone = template.clone();
198
  clone.find("div p").html(data.messages.slice(-1)[0].content);
199
  clone.removeAttr("id");
200
  chatbox.append(clone);
201
  chatbox.scrollTop(chatbox[0].scrollHeight);
202
-
203
  $("button").prop("disabled", false);
204
  $("#input-text").prop("disabled", false);
205
-
 
206
  messages = data.messages;
207
  localStorage.setItem("messages", JSON.stringify(messages));
208
  Prism.highlightAll();
@@ -258,6 +258,10 @@ function sendMessageStream(){
258
  chatbox.scrollTop(chatbox[0].scrollHeight);
259
  messages.push({role:"user", content:message});
260
 
 
 
 
 
261
 
262
  fetch("/chat_stream", {
263
  method: "POST",
@@ -271,13 +275,7 @@ function sendMessageStream(){
271
  }
272
  })
273
  .then(response => {
274
- //Verifica el código de estado de la respuesta
275
- let clone = template.clone();
276
- clone.removeAttr("id");
277
- clone.find("div p").html("Cargando...");
278
- chatbox.append(clone);
279
- chatbox.scrollTop(chatbox[0].scrollHeight);
280
-
281
  if (response.status !== 200) {
282
  switch (response.status) {
283
  case 404:
@@ -286,7 +284,6 @@ function sendMessageStream(){
286
  break;
287
  case 408:
288
  clone.find("div p").html(response);
289
- console.log(response)
290
  clone.addClass("warning");
291
  messages.pop();
292
  $("button").prop("disabled", false);
@@ -298,47 +295,42 @@ function sendMessageStream(){
298
  clone.addClass("error");
299
  break;
300
  }
301
- chatbox.append(clone);
302
  chatbox.scrollTop(chatbox[0].scrollHeight);
303
  return false
304
  }
305
- // console.log("response")
306
- // console.log(response)
307
- // response.headers.forEach((value,key) => console.log("header:",key,value))
308
- // console.log("------")
309
- //Obtiene el objeto de lectura de la respuesta
310
  let reader = response.body.getReader();
311
  let decoder = new TextDecoder();
312
- let outdata = "";
313
  return readChunk();
314
 
315
- function readChunk() {
316
  return reader.read().then( result => {
317
  if (!result.done) {
318
- let chunk = JSON.parse(decoder.decode(result.value))
319
- // console.log('got chunk of', chunk.length, 'bytes')
320
- // console.log(chunk);
321
- // console.log("*******")
322
- // console.log('recursing')
323
- if(chunk.type == "content"){
324
- outdata += chunk.content;
325
- clone.find("div p").html(outdata);
326
- chatbox.scrollTop(chatbox[0].scrollHeight);
327
- Prism.highlightAll();
328
- }else if(chunk.type == "config"){
329
- token = chunk.token ;
330
- }
331
- return readChunk();
332
-
333
  } else {
334
- messages.push({role:"user", content:outdata});
 
335
  chatbox.scrollTop(chatbox[0].scrollHeight);
 
336
  $("button").prop("disabled", false);
337
  $("#input-text").prop("disabled", false);
338
- $("#input-text").focus();
339
-
340
- // console.log('end')
341
 
 
 
 
 
 
 
342
  }
343
  });
344
  }
@@ -351,5 +343,6 @@ function sendMessageStream(){
351
  chatbox.append(clone);
352
  chatbox.scrollTop(chatbox[0].scrollHeight);
353
  console.log('Error: ', error);
 
354
  });
355
  }
 
5
  temperature: 1.0,
6
  frequency_penalty: 0.0,
7
  presence_penalty: 0.0,
8
+ stream: true
9
  }
10
  $(document).ready(function() {
11
 
 
27
  $("#input-text").keypress(function(event){
28
  if (!event.shiftKey && event.keyCode === 13) {
29
  event.preventDefault();
30
+ if(config.stream){
31
  sendMessageStream();
32
  }else{
33
  sendMessage();
 
38
 
39
  $("#input-send").click(function(event) {
40
  event.preventDefault();
41
+ if(config.stream){
42
  sendMessageStream();
43
  }else{
44
  sendMessage();
 
53
  temperature: 1.0,
54
  frequency_penalty: 0.0,
55
  presence_penalty: 0.0,
56
+ stream: true
57
  }
58
  $("#input-text").val("");
59
  recaularTextbox();
 
193
  config: config
194
  }),
195
  success: function(data) {
 
196
  let clone = template.clone();
197
  clone.find("div p").html(data.messages.slice(-1)[0].content);
198
  clone.removeAttr("id");
199
  chatbox.append(clone);
200
  chatbox.scrollTop(chatbox[0].scrollHeight);
201
+
202
  $("button").prop("disabled", false);
203
  $("#input-text").prop("disabled", false);
204
+
205
+ token = data.token;
206
  messages = data.messages;
207
  localStorage.setItem("messages", JSON.stringify(messages));
208
  Prism.highlightAll();
 
258
  chatbox.scrollTop(chatbox[0].scrollHeight);
259
  messages.push({role:"user", content:message});
260
 
261
+ clone = template.clone();
262
+ clone.removeAttr("id");
263
+ clone.find("div p").html("Cargando...");
264
+ chatbox.append(clone);
265
 
266
  fetch("/chat_stream", {
267
  method: "POST",
 
275
  }
276
  })
277
  .then(response => {
278
+
 
 
 
 
 
 
279
  if (response.status !== 200) {
280
  switch (response.status) {
281
  case 404:
 
284
  break;
285
  case 408:
286
  clone.find("div p").html(response);
 
287
  clone.addClass("warning");
288
  messages.pop();
289
  $("button").prop("disabled", false);
 
295
  clone.addClass("error");
296
  break;
297
  }
 
298
  chatbox.scrollTop(chatbox[0].scrollHeight);
299
  return false
300
  }
301
+ console.log("response")
302
+ console.log(response)
303
+ response.headers.forEach((value,key) => console.log("header:",key,value))
304
+ console.log("------")
305
+
306
  let reader = response.body.getReader();
307
  let decoder = new TextDecoder();
 
308
  return readChunk();
309
 
310
+ function readChunk(data="") {
311
  return reader.read().then( result => {
312
  if (!result.done) {
313
+ let chunk = decoder.decode(result.value)
314
+ console.log('got chunk of', chunk.length, 'bytes')
315
+ console.log(chunk);
316
+ console.log("*******")
317
+ console.log('recursing')
318
+ data += chunk;
319
+ return readChunk(data);
 
 
 
 
 
 
 
 
320
  } else {
321
+ data = JSON.parse(data);
322
+ clone.find("div p").html(data.content);
323
  chatbox.scrollTop(chatbox[0].scrollHeight);
324
+
325
  $("button").prop("disabled", false);
326
  $("#input-text").prop("disabled", false);
 
 
 
327
 
328
+ token = data.token;
329
+ messages.push({role: data.role, content: data.content}) ;
330
+ localStorage.setItem("messages", JSON.stringify(messages));
331
+ Prism.highlightAll();
332
+ $("#input-text").focus();
333
+ return data;
334
  }
335
  });
336
  }
 
343
  chatbox.append(clone);
344
  chatbox.scrollTop(chatbox[0].scrollHeight);
345
  console.log('Error: ', error);
346
+ return false
347
  });
348
  }