paola1 commited on
Commit
811e0e2
·
verified ·
1 Parent(s): 693c4f2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -32
app.py CHANGED
@@ -1,7 +1,9 @@
1
  from fastapi import FastAPI, HTTPException
 
2
  from pydantic import BaseModel
3
  import requests
4
  import json
 
5
 
6
  app = FastAPI()
7
 
@@ -33,38 +35,39 @@ async def chat(request: ChatRequest):
33
  "max_tokens": request.max_tokens
34
  }
35
 
36
- # Make the POST request with streaming
37
- try:
38
- with requests.post(url, headers=headers, data=json.dumps(payload), stream=True) as response:
39
- # Check if the request was successful
40
- if response.status_code == 200:
41
- result = ""
42
- # Stream the response
43
- for line in response.iter_lines():
44
- if line:
45
- # Decode the line
46
- decoded_line = line.decode('utf-8')
47
-
48
- # Check if the line starts with "data: "
49
- if decoded_line.startswith("data: "):
50
- # Extract the JSON part
51
- json_data = decoded_line[6:] # Remove "data: " prefix
52
-
53
- # Parse the JSON
54
- try:
55
- parsed_data = json.loads(json_data)
56
- # Check if 'choices' and 'delta' exist and append the content
57
- if 'choices' in parsed_data and len(parsed_data['choices']) > 0:
58
- content = parsed_data['choices'][0]['delta'].get('content', '')
59
- if content:
60
- result += content
61
- except json.JSONDecodeError:
62
- continue
63
- return {"response": result}
64
- else:
65
- raise HTTPException(status_code=response.status_code, detail=response.text)
66
- except Exception as e:
67
- raise HTTPException(status_code=500, detail=str(e))
 
68
 
69
  if __name__ == "__main__":
70
  import uvicorn
 
1
  from fastapi import FastAPI, HTTPException
2
+ from fastapi.responses import StreamingResponse
3
  from pydantic import BaseModel
4
  import requests
5
  import json
6
+ import asyncio
7
 
8
  app = FastAPI()
9
 
 
35
  "max_tokens": request.max_tokens
36
  }
37
 
38
+ # Function to stream the response
39
+ async def event_stream():
40
+ try:
41
+ with requests.post(url, headers=headers, data=json.dumps(payload), stream=True) as response:
42
+ # Check if the request was successful
43
+ if response.status_code == 200:
44
+ # Stream the response
45
+ for line in response.iter_lines():
46
+ if line:
47
+ # Decode the line
48
+ decoded_line = line.decode('utf-8')
49
+
50
+ # Check if the line starts with "data: "
51
+ if decoded_line.startswith("data: "):
52
+ # Extract the JSON part
53
+ json_data = decoded_line[6:] # Remove "data: " prefix
54
+
55
+ # Parse the JSON
56
+ try:
57
+ parsed_data = json.loads(json_data)
58
+ # Check if 'choices' and 'delta' exist and yield the content
59
+ if 'choices' in parsed_data and len(parsed_data['choices']) > 0:
60
+ content = parsed_data['choices'][0]['delta'].get('content', '')
61
+ if content:
62
+ yield content
63
+ except json.JSONDecodeError:
64
+ continue
65
+ else:
66
+ raise HTTPException(status_code=response.status_code, detail=response.text)
67
+ except Exception as e:
68
+ raise HTTPException(status_code=500, detail=str(e))
69
+
70
+ return StreamingResponse(event_stream(), media_type="text/event-stream")
71
 
72
  if __name__ == "__main__":
73
  import uvicorn