AxL95 commited on
Commit
ab6a52d
·
verified ·
1 Parent(s): 032d01b

Update chat.py

Browse files
Files changed (1) hide show
  1. chat.py +12 -12
chat.py CHANGED
@@ -7,7 +7,7 @@ from sentence_transformers import SentenceTransformer
7
  from sklearn.metrics.pairwise import cosine_similarity
8
  import re
9
  import json
10
-
11
  from auth import get_current_user
12
  from database import get_db
13
  from config import HF_TOKEN, MAX_TOKENS, EMBEDDING_MODEL
@@ -343,16 +343,12 @@ async def chat(request: Request):
343
  if chunk.choices and chunk.choices[0].delta.content:
344
  content = chunk.choices[0].delta.content
345
  collected_response += content
346
- chunk_buffer += content
347
- chunk_count += 1
348
 
349
- if chunk_count >= MAX_CHUNKS_BEFORE_SEND or '\n' in content:
350
- yield f"data: {json.dumps({'content': chunk_buffer})}\n\n"
351
- chunk_buffer = ""
352
- chunk_count = 0
353
-
354
- if chunk_buffer:
355
- yield f"data: {json.dumps({'content': chunk_buffer})}\n\n"
356
 
357
  if collected_response.endswith((".", "!", "?")) == False and len(collected_response) > 500:
358
  suffix = "\n\n(Note: Ma réponse a été limitée par des contraintes de taille. N'hésitez pas à me demander de poursuivre si vous souhaitez plus d'informations.)"
@@ -401,5 +397,9 @@ async def chat(request: Request):
401
 
402
  return StreamingResponse(
403
  generate_stream(),
404
- media_type="text/event-stream"
405
- )
 
 
 
 
 
7
  from sklearn.metrics.pairwise import cosine_similarity
8
  import re
9
  import json
10
+ import asyncio
11
  from auth import get_current_user
12
  from database import get_db
13
  from config import HF_TOKEN, MAX_TOKENS, EMBEDDING_MODEL
 
343
  if chunk.choices and chunk.choices[0].delta.content:
344
  content = chunk.choices[0].delta.content
345
  collected_response += content
 
 
346
 
347
+ # Envoyer chaque token individuellement sans buffering
348
+ yield f"data: {json.dumps({'content': content})}\n\n"
349
+
350
+ # Petit sleep pour éviter le buffering par le serveur ASGI
351
+ await asyncio.sleep(0)
 
 
352
 
353
  if collected_response.endswith((".", "!", "?")) == False and len(collected_response) > 500:
354
  suffix = "\n\n(Note: Ma réponse a été limitée par des contraintes de taille. N'hésitez pas à me demander de poursuivre si vous souhaitez plus d'informations.)"
 
397
 
398
  return StreamingResponse(
399
  generate_stream(),
400
+ media_type="text/event-stream",
401
+ headers={
402
+ "Cache-Control": "no-cache, no-transform",
403
+ "X-Accel-Buffering": "no" # Important pour Nginx
404
+ }
405
+ )