Niansuh commited on
Commit
1eae6af
·
verified ·
1 Parent(s): 6b34973

Update api/utils.py

Browse files
Files changed (1) hide show
  1. api/utils.py +31 -27
api/utils.py CHANGED
@@ -17,42 +17,46 @@ async def process_streaming_response(request: ChatRequest):
17
  messages = [msg.dict() for msg in request.messages]
18
 
19
  try:
20
- async for content in AmigoChat.generate_response(
21
- model=request.model,
22
- messages=messages,
23
- stream=True
24
- ):
25
- timestamp = int(datetime.now().timestamp())
26
- yield json.dumps({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  "id": f"chatcmpl-{uuid.uuid4()}",
28
  "object": "chat.completion.chunk",
29
- "created": timestamp,
30
  "model": request.model,
31
  "choices": [
32
  {
33
  "index": 0,
34
- "delta": {"content": content},
35
- "finish_reason": None,
36
  }
37
  ],
38
- "usage": None,
39
- }) + "\n"
 
40
 
41
- # Indicate the end of the stream
42
- yield json.dumps({
43
- "id": f"chatcmpl-{uuid.uuid4()}",
44
- "object": "chat.completion.chunk",
45
- "created": int(datetime.now().timestamp()),
46
- "model": request.model,
47
- "choices": [
48
- {
49
- "index": 0,
50
- "delta": {},
51
- "finish_reason": "stop",
52
- }
53
- ],
54
- "usage": None,
55
- }) + "\n"
56
 
57
  except Exception as e:
58
  logger.error(f"Error in streaming response: {e}")
 
17
  messages = [msg.dict() for msg in request.messages]
18
 
19
  try:
20
+ async def event_generator():
21
+ async for content in AmigoChat.generate_response(
22
+ model=request.model,
23
+ messages=messages,
24
+ stream=True
25
+ ):
26
+ timestamp = int(datetime.now().timestamp())
27
+ chunk = {
28
+ "id": f"chatcmpl-{uuid.uuid4()}",
29
+ "object": "chat.completion.chunk",
30
+ "created": timestamp,
31
+ "model": request.model,
32
+ "choices": [
33
+ {
34
+ "index": 0,
35
+ "delta": {"content": content},
36
+ "finish_reason": None,
37
+ }
38
+ ],
39
+ }
40
+ yield f"data: {json.dumps(chunk)}\n\n"
41
+
42
+ # Indicate the end of the stream
43
+ end_chunk = {
44
  "id": f"chatcmpl-{uuid.uuid4()}",
45
  "object": "chat.completion.chunk",
46
+ "created": int(datetime.now().timestamp()),
47
  "model": request.model,
48
  "choices": [
49
  {
50
  "index": 0,
51
+ "delta": {},
52
+ "finish_reason": "stop",
53
  }
54
  ],
55
+ }
56
+ yield f"data: {json.dumps(end_chunk)}\n\n"
57
+ yield "data: [DONE]\n\n"
58
 
59
+ return event_generator()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  except Exception as e:
62
  logger.error(f"Error in streaming response: {e}")