Sergidev commited on
Commit
2f9891f
1 Parent(s): 5f18a0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -3
app.py CHANGED
@@ -37,15 +37,31 @@ async def chat(request: Request, background_tasks: BackgroundTasks):
37
  user_input = data["user_input"]
38
  mode = data["mode"]
39
 
40
- async def stream_response():
41
- async for chunk in process_request(user_input, mode):
 
 
 
 
42
  yield chunk
43
 
44
- return StreamingResponse(stream_response(), media_type="text/plain")
45
  except Exception as e:
46
  print(f"[SYSTEM] Error: {str(e)}")
47
  return {"error": str(e)}
48
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  @app.post("/sleep")
50
  async def sleep():
51
  try:
 
37
  user_input = data["user_input"]
38
  mode = data["mode"]
39
 
40
+ async def response_generator():
41
+ future = asyncio.Future()
42
+ request_queue.put((future, user_input, mode))
43
+ await future
44
+
45
+ async for chunk in future.result():
46
  yield chunk
47
 
48
+ return StreamingResponse(response_generator(), media_type="text/plain")
49
  except Exception as e:
50
  print(f"[SYSTEM] Error: {str(e)}")
51
  return {"error": str(e)}
52
 
53
+ async def queue_worker():
54
+ while True:
55
+ if not request_queue.empty():
56
+ future, user_input, mode = request_queue.get()
57
+ result = process_request(user_input, mode)
58
+ future.set_result(result)
59
+ await asyncio.sleep(0.1)
60
+
61
+ @app.on_event("startup")
62
+ async def startup_event():
63
+ asyncio.create_task(queue_worker())
64
+
65
  @app.post("/sleep")
66
  async def sleep():
67
  try: