Update app.py
Browse files
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 |
-
#
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
|
|
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
|