Skip to content
This repository was archived by the owner on Jun 7, 2025. It is now read-only.

Commit 73ee405

Browse files
committed
Modifica il servizio chat per restituire risposte in streaming e aggiorna i requisiti per includere starlette
1 parent abfd5e7 commit 73ee405

File tree

3 files changed

+34
-4
lines changed

3 files changed

+34
-4
lines changed

app/routes/chroma.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,4 @@ async def create_chat_response(domanda: schemas.Question):
1313

1414
contesto = embedding(domanda.question)
1515
# print(contesto)
16-
risposta = chat(domanda.question, contesto)
17-
return {"answer": risposta}
16+
return chat(domanda.question, contesto)

app/services/chat_services.py

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import os
22
from dotenv import load_dotenv
33
from fastapi import HTTPException
4+
from starlette.responses import StreamingResponse
45
import logging
6+
import json
57

68
logger = logging.getLogger(__name__)
79

@@ -25,12 +27,40 @@ def chat(domanda, contesto):
2527
{"role": "user", "content": f"Contesto: {contesto}"},
2628
{"role": "user", "content": f"Domanda: {domanda}"},
2729
],
30+
stream=True,
2831
)
2932

30-
testo_risposta = risposta.choices[0].message.content
31-
return testo_risposta
33+
def async_generator():
34+
for chunk in risposta:
35+
logging.debug(f"Received chunk: {chunk}")
36+
37+
response_data = {
38+
"id": chunk.id,
39+
"object": chunk.object,
40+
"created": chunk.created,
41+
"model": chunk.model,
42+
"system_fingerprint": chunk.system_fingerprint,
43+
"choices": [
44+
{
45+
"index": chunk.choices[0].index,
46+
"delta": {
47+
"content": getattr(
48+
chunk.choices[0].delta, "content", None
49+
)
50+
},
51+
"finish_reason": chunk.choices[0].finish_reason,
52+
}
53+
],
54+
}
55+
yield f"data: {json.dumps(response_data)}\n\n"
56+
57+
return StreamingResponse(async_generator(), media_type="text/event-stream")
58+
59+
# testo_risposta = risposta.choices[0].message.content
60+
# return testo_risposta
3261

3362
except Exception as e:
63+
logger.error(f"Errore nel servizio chat: {str(e)}", exc_info=True)
3464
raise HTTPException(
3565
status_code=500, detail=f"Errore nel servizio chat: {str(e)}"
3666
)

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# required packages
22
fastapi
33
uvicorn
4+
starlette
45
#psycopg2
56
#pymilvus
67
#pymilvus[model]

0 commit comments

Comments
 (0)