main.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import asyncio
  2. import socketio
  3. from open_webui.apps.webui.models.users import Users
  4. from open_webui.config 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=(
  10. ["polling", "websocket"] if ENABLE_WEBSOCKET_SUPPORT.value else ["polling"]
  11. ),
  12. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT.value,
  13. )
  14. app = socketio.ASGIApp(sio, socketio_path="/ws/socket.io")
  15. # Dictionary to maintain the user pool
  16. SESSION_POOL = {}
  17. USER_POOL = {}
  18. USAGE_POOL = {}
  19. # Timeout duration in seconds
  20. TIMEOUT_DURATION = 3
  21. @sio.event
  22. async def connect(sid, environ, auth):
  23. user = None
  24. if auth and "token" in auth:
  25. data = decode_token(auth["token"])
  26. if data is not None and "id" in data:
  27. user = Users.get_user_by_id(data["id"])
  28. if user:
  29. SESSION_POOL[sid] = user.id
  30. if user.id in USER_POOL:
  31. USER_POOL[user.id].append(sid)
  32. else:
  33. USER_POOL[user.id] = [sid]
  34. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  35. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  36. await sio.emit("usage", {"models": get_models_in_use()})
  37. @sio.on("user-join")
  38. async def user_join(sid, data):
  39. print("user-join", sid, data)
  40. auth = data["auth"] if "auth" in data else None
  41. if not auth or "token" not in auth:
  42. return
  43. data = decode_token(auth["token"])
  44. if data is None or "id" not in data:
  45. return
  46. user = Users.get_user_by_id(data["id"])
  47. if not user:
  48. return
  49. SESSION_POOL[sid] = user.id
  50. if user.id in USER_POOL:
  51. USER_POOL[user.id].append(sid)
  52. else:
  53. USER_POOL[user.id] = [sid]
  54. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  55. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  56. @sio.on("user-count")
  57. async def user_count(sid):
  58. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  59. def get_models_in_use():
  60. # Aggregate all models in use
  61. models_in_use = []
  62. for model_id, data in USAGE_POOL.items():
  63. models_in_use.append(model_id)
  64. return models_in_use
  65. @sio.on("usage")
  66. async def usage(sid, data):
  67. model_id = data["model"]
  68. # Cancel previous callback if there is one
  69. if model_id in USAGE_POOL:
  70. USAGE_POOL[model_id]["callback"].cancel()
  71. # Store the new usage data and task
  72. if model_id in USAGE_POOL:
  73. USAGE_POOL[model_id]["sids"].append(sid)
  74. USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
  75. else:
  76. USAGE_POOL[model_id] = {"sids": [sid]}
  77. # Schedule a task to remove the usage data after TIMEOUT_DURATION
  78. USAGE_POOL[model_id]["callback"] = asyncio.create_task(
  79. remove_after_timeout(sid, model_id)
  80. )
  81. # Broadcast the usage data to all clients
  82. await sio.emit("usage", {"models": get_models_in_use()})
  83. async def remove_after_timeout(sid, model_id):
  84. try:
  85. await asyncio.sleep(TIMEOUT_DURATION)
  86. if model_id in USAGE_POOL:
  87. print(USAGE_POOL[model_id]["sids"])
  88. USAGE_POOL[model_id]["sids"].remove(sid)
  89. USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
  90. if len(USAGE_POOL[model_id]["sids"]) == 0:
  91. del USAGE_POOL[model_id]
  92. # Broadcast the usage data to all clients
  93. await sio.emit("usage", {"models": get_models_in_use()})
  94. except asyncio.CancelledError:
  95. # Task was cancelled due to new 'usage' event
  96. pass
  97. @sio.event
  98. async def disconnect(sid):
  99. if sid in SESSION_POOL:
  100. user_id = SESSION_POOL[sid]
  101. del SESSION_POOL[sid]
  102. USER_POOL[user_id].remove(sid)
  103. if len(USER_POOL[user_id]) == 0:
  104. del USER_POOL[user_id]
  105. await sio.emit("user-count", {"count": len(USER_POOL)})
  106. else:
  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__