main.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import asyncio
  2. import socketio
  3. from open_webui.apps.webui.models.users import Users
  4. from open_webui.env import ENABLE_WEBSOCKET_SUPPORT
  5. from open_webui.utils.utils import decode_token
  6. sio = socketio.AsyncServer(
  7. cors_allowed_origins=[],
  8. async_mode="asgi",
  9. transports=(["polling", "websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]),
  10. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  11. always_connect=True,
  12. )
  13. app = socketio.ASGIApp(sio, socketio_path="/ws/socket.io")
  14. # Dictionary to maintain the user pool
  15. SESSION_POOL = {}
  16. USER_POOL = {}
  17. USAGE_POOL = {}
  18. # Timeout duration in seconds
  19. TIMEOUT_DURATION = 3
  20. @sio.event
  21. async def connect(sid, environ, auth):
  22. user = None
  23. if auth and "token" in auth:
  24. data = decode_token(auth["token"])
  25. if data is not None and "id" in data:
  26. user = Users.get_user_by_id(data["id"])
  27. if user:
  28. SESSION_POOL[sid] = user.id
  29. if user.id in USER_POOL:
  30. USER_POOL[user.id].append(sid)
  31. else:
  32. USER_POOL[user.id] = [sid]
  33. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  34. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  35. await sio.emit("usage", {"models": get_models_in_use()})
  36. @sio.on("user-join")
  37. async def user_join(sid, data):
  38. # print("user-join", sid, data)
  39. auth = data["auth"] if "auth" in data else None
  40. if not auth or "token" not in auth:
  41. return
  42. data = decode_token(auth["token"])
  43. if data is None or "id" not in data:
  44. return
  45. user = Users.get_user_by_id(data["id"])
  46. if not user:
  47. return
  48. SESSION_POOL[sid] = user.id
  49. if user.id in USER_POOL:
  50. USER_POOL[user.id].append(sid)
  51. else:
  52. USER_POOL[user.id] = [sid]
  53. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  54. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  55. @sio.on("user-count")
  56. async def user_count(sid):
  57. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  58. def get_models_in_use():
  59. # Aggregate all models in use
  60. models_in_use = []
  61. for model_id, data in USAGE_POOL.items():
  62. models_in_use.append(model_id)
  63. return models_in_use
  64. @sio.on("usage")
  65. async def usage(sid, data):
  66. model_id = data["model"]
  67. # Cancel previous callback if there is one
  68. if model_id in USAGE_POOL:
  69. USAGE_POOL[model_id]["callback"].cancel()
  70. # Store the new usage data and task
  71. if model_id in USAGE_POOL:
  72. USAGE_POOL[model_id]["sids"].append(sid)
  73. USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
  74. else:
  75. USAGE_POOL[model_id] = {"sids": [sid]}
  76. # Schedule a task to remove the usage data after TIMEOUT_DURATION
  77. USAGE_POOL[model_id]["callback"] = asyncio.create_task(
  78. remove_after_timeout(sid, model_id)
  79. )
  80. # Broadcast the usage data to all clients
  81. await sio.emit("usage", {"models": get_models_in_use()})
  82. async def remove_after_timeout(sid, model_id):
  83. try:
  84. await asyncio.sleep(TIMEOUT_DURATION)
  85. if model_id in USAGE_POOL:
  86. # print(USAGE_POOL[model_id]["sids"])
  87. USAGE_POOL[model_id]["sids"].remove(sid)
  88. USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
  89. if len(USAGE_POOL[model_id]["sids"]) == 0:
  90. del USAGE_POOL[model_id]
  91. # Broadcast the usage data to all clients
  92. await sio.emit("usage", {"models": get_models_in_use()})
  93. except asyncio.CancelledError:
  94. # Task was cancelled due to new 'usage' event
  95. pass
  96. @sio.event
  97. async def disconnect(sid):
  98. if sid in SESSION_POOL:
  99. user_id = SESSION_POOL[sid]
  100. del SESSION_POOL[sid]
  101. USER_POOL[user_id].remove(sid)
  102. if len(USER_POOL[user_id]) == 0:
  103. del USER_POOL[user_id]
  104. await sio.emit("user-count", {"count": len(USER_POOL)})
  105. else:
  106. pass
  107. # print(f"Unknown session ID {sid} disconnected")
  108. def get_event_emitter(request_info):
  109. async def __event_emitter__(event_data):
  110. await sio.emit(
  111. "chat-events",
  112. {
  113. "chat_id": request_info["chat_id"],
  114. "message_id": request_info["message_id"],
  115. "data": event_data,
  116. },
  117. to=request_info["session_id"],
  118. )
  119. return __event_emitter__
  120. def get_event_call(request_info):
  121. async def __event_call__(event_data):
  122. response = await sio.call(
  123. "chat-events",
  124. {
  125. "chat_id": request_info["chat_id"],
  126. "message_id": request_info["message_id"],
  127. "data": event_data,
  128. },
  129. to=request_info["session_id"],
  130. )
  131. return response
  132. return __event_call__